2011-01-28 78 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