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