2011-01-28 60 views
2

給出一個自定義屬性,我想它的目標的名稱:C#獲取的MemberInfo自定義屬性的目標

public class Example 
{ 
    [Woop] ////// basically I want to get "Size" datamember name from the attribute 
    public float Size; 
} 

public class Tester 
{ 
    public static void Main() 
    { 
     Type type = typeof(Example); 
     object[] attributes = type.GetCustomAttributes(typeof(WoopAttribute), false); 

     foreach (var attribute in attributes) 
     { 
      // I have the attribute, but what is the name of it's target? (Example.Size) 
      attribute.GetTargetName(); //?? 
     } 
    } 
} 

希望很清楚!

回答

6

做的其他方式:

迭代

MemberInfo[] members = type.GetMembers(); 

,並要求

Object[] myAttributes = members[i].GetCustomAttributes(true); 

foreach(MemberInfo member in type.GetMembers()) { 
    Object[] myAttributes = member.GetCustomAttributes(typeof(WoopAttribute),true); 
    if(myAttributes.Length > 0) 
    { 
     MemberInfo woopmember = member; //<--- gotcha 
    } 
} 

但使用LINQ好得多:

var members = from member in type.GetMembers() 
    from attribute in member.GetCustomAttributes(typeof(WoopAttribute),true) 
    select member; 
+0

歡呼聲,我希望有一個直接訪問。但是,這工作得很好。我會擔心一次(或IF),我會得到性能問題 – 2011-01-29 00:21:40