开发者

Getting attributes for a property where there isn't a direct reference

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 = ne开发者_Python百科w Bar();

    DoStuff(x.Stuff);
}

void DoStuff(Enum z) {

    // How do I get the DisaplyAttribute from here?
}


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.


Type t = typeof(Bar);
PropertyInfo pi = t.GetProperty("Stuff");
Attribute[] att = pi.GetCustomAttributes(typeof(DisplayAttribute), true);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜