Reputation:
How do I get attributes of the Stuff property from the DoStuff() method? Is this possible?
public class Bar
{
public enum FooZ
{
Hello,
GoodBye
}
[Display("Hello"]
public FooZ Stuff { get; set; }
public Bar() {
Stuff = FooZ.GoodBye;
}
}
void Main()
{
var x = new Bar();
DoStuff(x.Stuff);
}
void DoStuff(Enum z) {
// How do I get the DisaplyAttribute from here?
}
Upvotes: 0
Views: 77
Reputation: 113472
You can't. The parameter z
doesn't remember where it came from; values don't remember how they were constructed. Remember that in this case, the property is what is decorated with the attribute (meaning that it is embedded in the containing-type's metadata), not the value returned by its getter. You have to reflect the Bar
type itself, as in Itay's answer.
Upvotes: 2
Reputation: 18296
Type t = typeof(Bar);
PropertyInfo pi = t.GetProperty("Stuff");
Attribute[] att = pi.GetCustomAttributes(typeof(DisplayAttribute), true);
Upvotes: 1