开发者

C# Get memberinfo for custom attribute's target

Given a custom attribute, I want to get the name of it开发者_开发百科s target:

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

Hope it's clear!


do it the other way around:

iterate

 MemberInfo[] members = type.GetMembers();

and request

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

or

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

but much nicer with Linq:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜