[英]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? 如何从DoStuff()方法获取Stuff属性的属性? 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; 参数
z
不记得它来自何处; 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.
请记住,在这种情况下, 属性是用属性修饰的内容(意味着它嵌入在包含类型的元数据中),而不是其getter返回的值。 You have to reflect the
Bar
type itself, as in Itay's answer. 您必须像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.