[英]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.