2012-04-25 11 views
5

मैं निर्धारित कस्टम विशेषताGetCustomAttributes वापस नहीं करता है मूल्य

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

    public string Field 
    { 
     get { return field; } 

    } 
} 

मेरी कक्षा जो कस्टम विशेषता का उपयोग करता है

[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; } 


    } 
} 

नीचे लेकिन जब के रूप में मैं कस्टम विशेषता के मान प्राप्त करने की कोशिश यह शून्य ऑब्जेक्ट

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. 
} 

मुझे क्या याद आ रही है?

+2

'लिखने में कोई त्रुटि FieldAttributes' है:

इसके अलावा, इस आसान उपयोग (विशेषता यह सोचते हैं डुप्लिकेट अनुमति नहीं है) है? 'FieldAttribute' होना चाहिए? 'roperty' भी एक टाइपो है? –

+0

इसके अलावा - आप इसे किस टीई के साथ बुला रहे हैं? –

+0

यूप, टाइपो। उदाहरण के लिए, कॉलमनाम एट्रिब्यूट का बेहतर नाम उपयोग करें। या बस लिंक से एसक्यूएल का उपयोग करें जो एक ही चीज़ करता है। –

उत्तर

8

टाइपो: typeof(FieldAttribute) होना चाहिए। FieldAttributes नामक एक असंबंधित सिस्टम एनम है (System.Reflection में, जो आपके using निर्देशों में है, क्योंकि PropertyInfo सही ढंग से हल हो जाता है)।

var field = (FieldAttribute) Attribute.GetCustomAttribute(
      property, typeof (FieldAttribute), false); 
if(field != null) { 
    Console.WriteLine(field.Field); 
} 
संबंधित मुद्दे