पर गुण मैं इस तरह के एक वर्गजाओ विवरण कक्षा स्तर
[Description("This is a wahala class")]
public class Wahala
{
}
Wahala
वर्ग के लिए Description
विशेषता की सामग्री प्राप्त करने के लिए वैसे भी वहाँ है है?
पर गुण मैं इस तरह के एक वर्गजाओ विवरण कक्षा स्तर
[Description("This is a wahala class")]
public class Wahala
{
}
Wahala
वर्ग के लिए Description
विशेषता की सामग्री प्राप्त करने के लिए वैसे भी वहाँ है है?
बिल्कुल - 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;
}
}
कोड की ही तरह इस तरह के क्षेत्रों, गुण आदि
उपयोग प्रतिबिंब और Attribute.GetCustomAttributes
आप कर सकते हैं के रूप में अन्य सदस्यों के लिए विवरण, प्राप्त कर सकते हैं विशेषता डेटा पढ़ने के लिए प्रतिबिंब का उपयोग करें:
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 से अनुकूलित।
क्यों "foreach"? क्या कई विवरण हैं? –
@ जॉर्जबिरबिलिस - वहां हो सकता है। – Oded
+1 ऑब्जेक्ट के लिए बस एक विस्तार विधि में बदल गया :) –
यदि कई विवरण हो सकते हैं, तो शायद उन्हें नई लाइनों के साथ जोड़ दें? –
बीटीडब्ल्यू, यदि आप पीसीएल पर पोर्ट करते हैं तो इसे ध्यान में रखें: http://stackoverflow.com/questions/18912697/system-componentmodel-descriptionattribute-in-portable-class-library/23906297 –