2012-04-25 44 views
5

tôi đã xác định một thuộc tính tùy chỉnhGetCustomAttributes không trả lại giá trị

[AttributeUsage(AttributeTargets.Property)] 
public class FieldAttribute: Attribute 
{ 
    public FieldAttribute(string field) 
    { 
     this.field = field; 
    } 
    private string field; 

    public string Field 
    { 
     get { return field; } 

    } 
} 

Lớp của tôi trong đó sử dụng các thuộc tính tùy chỉnh như sau

[Serializable()] 
public class DocumentMaster : DomainBase 
{ 

    [Field("DOC_CODE")] 
    public string DocumentCode { get; set; } 


    [Field("DOC_NAME")] 
    public string DocumentName { get; set; } 


    [Field("REMARKS")] 
    public string Remarks { get; set; } 


    } 
} 

Nhưng khi tôi cố gắng để có được giá trị của thuộc tính tùy chỉnh nó trả về đối tượng null

Type typeOfT = typeof(T); 
T obj = Activator.CreateInstance<T>(); 

PropertyInfo[] propInfo = typeOfT.GetProperties(); 

foreach (PropertyInfo property in propInfo) 
{ 

    object[] colName = roperty.GetCustomAttributes(typeof(FieldAttributes), false); 
    /// colName has no values. 
} 

Tôi đang thiếu gì?

+2

là 'FieldAttributes' một lỗi đánh máy? nên là 'FieldAttribute'? là 'roperty' cũng là lỗi đánh máy? –

+0

Ngoài ra - những gì 'T' bạn đang gọi nó với? –

+0

Yup, typo. Sử dụng tên tốt hơn, ColumnNameAttribute chẳng hạn. Hoặc chỉ cần sử dụng LINQ to SQL thực hiện điều tương tự. –

Trả lời

8

typo: phải là typeof(FieldAttribute). Có một hệ thống enum không liên quan được gọi là FieldAttributes (trong System.Reflection, mà bạn có trong chỉ thị using của mình, vì PropertyInfo giải quyết chính xác).

Ngoài ra, đây là việc sử dụng dễ dàng hơn (giả sử các thuộc tính không cho phép bản sao):

var field = (FieldAttribute) Attribute.GetCustomAttribute(
      property, typeof (FieldAttribute), false); 
if(field != null) { 
    Console.WriteLine(field.Field); 
} 
Các vấn đề liên quan