2010-07-20 37 views
22

Tôi đã thuộc tính sau tùy chỉnh, có thể được áp dụng trên các thuộc tính:thuộc tính Custom trên tài sản - loại và giá trị của tài sản do Bắt

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

Ví dụ:

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

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

Sẽ cũng được các lớp khác, mà các thuộc tính định danh có thể được thêm vào tính chất của loại khác nhau:

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

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

    public string SomeOtherProperty { get; set; } 
} 

Sau đó tôi cần để có thể nhận được thông tin này trong lớp học tiêu thụ của tôi. Ví dụ:

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

Cách tốt nhất để thực hiện việc này là gì? Tôi cần lấy loại trường [Identifier()] (int, string, etc ...) và giá trị thực, rõ ràng là dựa trên loại.

Trả lời

30

Something như sau ,, này sẽ chỉ sử dụng các tài sản đầu tiên nói đến accross có thuộc tính, tất nhiên bạn có thể đặt nó trên nhiều hơn một ..

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

nhờ - có thể' t sử dụng "prop" trong lambda trong FirstOrDefault, nhưng tôi đã sắp xếp nó :-) – Alex

+0

Ahh có, đã được viết nó trong notepad ;-) cố định. –

+1

Tôi đã đánh dấu thuộc tính của mình bằng [Identifier()] nhưng .GetProperties() trả về tất cả các thuộc tính khác EXCEPT this ?! thuộc tính của tôi dường như ẩn nó ?? – 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) 
    } 
} 
Các vấn đề liên quan