简体   繁体   中英

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 = new 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM