繁体   English   中英

获取没有直接引用的属性的属性

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

如何从DoStuff()方法获取Stuff属性的属性? 这可能吗?

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?
}

你不能 参数z不记得它来自何处; 值不记得它们是如何构造的。 请记住,在这种情况下, 属性是用属性修饰的内容(意味着它嵌入在包含类型的元数据中),而不是其getter返回的值。 您必须像Itay的回答一样反映Bar类型本身。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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