C#获取自定义属性目标的memberinfo

时间:2011-01-28 22:37:56

标签: c# reflection

鉴于自定义属性,我想获取其目标的名称:

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(); //??
        }
    }
}

希望它清楚!

1 个答案:

答案 0 :(得分: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;