2010-07-20 7 views
22

Mam następujący atrybut niestandardowy, który może być stosowany na właściwości:Niestandardowy atrybut rzeczowych - Pierwsze rodzaju i wartości przypisanej własności

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] 
public class IdentifierAttribute : Attribute 
{ 
} 

Na przykład:

public class MyClass 
{ 
    [Identifier()] 
    public string Name { get; set; } 

    public int SomeNumber { get; set; } 
    public string SomeOtherProperty { get; set; } 
} 

Nie będzie również inne klasy, do których atrybut Identyfikator może zostać dodany do właściwości innego typu:

public class MyOtherClass 
{ 
    public string Name { get; set; } 

    [Identifier()] 
    public int SomeNumber { get; set; } 

    public string SomeOtherProperty { get; set; } 
} 

Muszę być w stanie uzyskać te informacje w mojej klasie konsumującej. Na przykład:

public class TestClass<T> 
{ 
    public void GetIDForPassedInObject(T obj) 
    { 
     var type = obj.GetType(); 
     //type.GetCustomAttributes(true)??? 
    } 
} 

Jaki jest najlepszy sposób postępowania w tej sprawie? Potrzebuję uzyskać typ pola [Identyfikator()] (int, string, etc ...) i rzeczywistą wartość, oczywiście w oparciu o typ.

Odpowiedz

30

Coś następujące ,, to będzie używać tylko pierwszą nieruchomość chodzi po drugiej stronie, który ma atrybut, oczywiście można umieścić go na więcej niż jednym ..

public object GetIDForPassedInObject(T obj) 
    { 
     var prop = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance) 
        .FirstOrDefault(p => p.GetCustomAttributes(typeof(IdentifierAttribute), false).Count() ==1); 
     object ret = prop !=null ? prop.GetValue(obj, null) : null; 

     return ret; 
    } 
+0

dzięki - może” t używaj "prop" w lambda w FirstOrDefault, ale posortowałem to :-) – Alex

+0

Ahh tak, pisałem to w notatniku ;-) Naprawiono. –

+1

Znacząco zaznaczyłem moją właściwość [Identyfikator()], ale właściwość .GetProperties() zwraca wszystkie pozostałe właściwości Z WYJĄTKIEM tego ?! mój atrybut wydaje się to ukrywać? – Alex

2
public class TestClass<T> 
{ 
    public void GetIDForPassedInObject(T obj) 
    { 
     PropertyInfo[] properties = 
      obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);    

     PropertyInfo IdProperty = (from PropertyInfo property in properties 
          where property.GetCustomAttributes(typeof(Identifier), true).Length > 0 
          select property).First(); 

     if(null == IdProperty) 
      throw new ArgumentException("obj does not have Identifier."); 

     Object propValue = IdProperty.GetValue(entity, null) 
    } 
} 
Powiązane problemy