2010-05-19 17 views
17

पर गुण मैं इस तरह के एक वर्गजाओ विवरण कक्षा स्तर

[Description("This is a wahala class")] 
public class Wahala 
{ 

} 

Wahala वर्ग के लिए Description विशेषता की सामग्री प्राप्त करने के लिए वैसे भी वहाँ है है?

उत्तर

29

बिल्कुल - Type.GetCustomAttributes का उपयोग करें। नमूना कोड:

using System; 
using System.ComponentModel; 

[Description("This is a wahala class")] 
public class Wahala 
{  
} 

public class Test 
{ 
    static void Main() 
    { 
     Console.WriteLine(GetDescription(typeof(Wahala))); 
    } 

    static string GetDescription(Type type) 
    { 
     var descriptions = (DescriptionAttribute[]) 
      type.GetCustomAttributes(typeof(DescriptionAttribute), false); 

     if (descriptions.Length == 0) 
     { 
      return null; 
     } 
     return descriptions[0].Description; 
    } 
} 

कोड की ही तरह इस तरह के क्षेत्रों, गुण आदि

+1

+1 ऑब्जेक्ट के लिए बस एक विस्तार विधि में बदल गया :) –

+0

यदि कई विवरण हो सकते हैं, तो शायद उन्हें नई लाइनों के साथ जोड़ दें? –

+1

बीटीडब्ल्यू, यदि आप पीसीएल पर पोर्ट करते हैं तो इसे ध्यान में रखें: http://stackoverflow.com/questions/18912697/system-componentmodel-descriptionattribute-in-portable-class-library/23906297 –

2

आप कर सकते हैं के रूप में अन्य सदस्यों के लिए विवरण, प्राप्त कर सकते हैं विशेषता डेटा पढ़ने के लिए प्रतिबिंब का उपयोग करें:

System.Reflection.MemberInfo inf = typeof(Wahala); 
object[] attributes; 
attributes = 
    inf.GetCustomAttributes(
     typeof(DescriptionAttribute), false); 

foreach(Object attribute in attributes) 
{ 
    DescriptionAttribute da = (DescriptionAttribute)attribute; 
    Console.WriteLine("Description: {0}", da.Description); 
} 

here से अनुकूलित।

+0

क्यों "foreach"? क्या कई विवरण हैं? –

+0

@ जॉर्जबिरबिलिस - वहां हो सकता है। – Oded

संबंधित मुद्दे