mercredi 11 février 2015

C# Get the class name owning the member an attribute is applied to

Here you have a simple Attribute Class



public class FooAttribute : Attribute
{
public FooAttribute(Type owner)
{
ClassName = owner.Name;
}

public string ClassName { get; set; }
}


Here is basic usage of it



public class Bar
{
[Foo(typeof(Bar))]
public double X { get; set; }
}


Current solution is explicitly passing in the type of the owning class, but if you have 100 properties on each of multiple classes then it becomes a cumbersom task to add the constructor parameter for every single Attribute.


Is there a way I could implicitly get the class name inside the FooAttribute from where it was used? Maybe something similar to the [CallerMemberName] attribute used for OnPropertyChanged methods?


Psudo example



public class FooAttribute : Attribute
{
public FooAttribute([CallerClassName] string className = null)
{
ClassName = className;
}

public string ClassName { get; set; }
}





Aucun commentaire:

Enregistrer un commentaire