2011-01-28 3 views
2

Учитывая пользовательский атрибут, я хочу, чтобы получить имя своей цели:C# Get 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

приветствия, я надеялся, что есть прямой доступ. Но это работает достаточно хорошо. Я буду беспокоиться об этом один раз (или ЕСЛИ), я получаю проблемы с производительностью, которые, как мне кажется –

Смежные вопросы