मुझे पता चला कि ऐसा करने के लिए मेरे लिए सबसे अच्छा तरीका System.ComponentModel. enum मानों पर डिस्क्रिप्शन विशेषता का उपयोग कर है।
using System.ComponentModel;
public enum ActionCode
{
[Description("E")]
Edit,
[Description("D")]
Delete,
[Description("R")]
Restore
}
फिर, इसका इस्तेमाल करने की, एक विस्तार विधि एक स्थिर वर्ग पर तो जैसे बनाने के लिए::
संपादित करें:
यहाँ एक उदाहरण है मैं एक सामान्य विस्तार पद्धति के रूप में मूल कोड दुबारा लिखा IConvertible
लागू करने वाली कक्षा पर (Enum
इस इंटरफ़ेस को लागू करता है, इसलिए यह जिस तरीके से हमें इसकी आवश्यकता है)।
public static string GetDescription<T>(this T e) where T : IConvertible
{
if (e is Enum)
{
Type type = e.GetType();
Array values = System.Enum.GetValues(type);
foreach (int val in values)
{
if (val == e.ToInt32(CultureInfo.InvariantCulture))
{
var memInfo = type.GetMember(type.GetEnumName(val));
var descriptionAttribute = memInfo[0]
.GetCustomAttributes(typeof(DescriptionAttribute), false)
.FirstOrDefault() as DescriptionAttribute;
if (descriptionAttribute != null)
{
return descriptionAttribute.Description;
}
}
}
}
return null; // could also return string.Empty
}
तो, स्ट्रिंग ऊपर हमारे enum के साथ जुड़े पाने के लिए, हम निम्नलिखित कोड का उपयोग कर सकता:
using Your.Extension.Method.Namespace;
...
ActionCode action = ActionCode.Edit;
string actionDescription = action.GetDescription();
// value of actionDescription will be "E"
यहाँ एक और है यहाँ एक सामान्य विधि है कि सभी enums पर काम करता है नमूना Enum:
:
public enum TestEnum
{
[Description("This is test 1")]
Test1,
[Description("This is test 2")]
Test2,
[Description("This is test 3")]
Test3
}
यहाँ विवरण देखने के लिए कोड है
TestEnum test = TestEnum.Test2;
var testDescription = test.GetDescription();
परिणाम होगा:
"This is test 2"
मैं आगे जाना है और सामान्य विधि पोस्ट के रूप में यह बहुत अधिक उपयोगी है चाहता था। यह आपको अपने सभी enums के लिए एक कस्टम एक्सटेंशन लिखने से रोकता है।
मैंने स्किम किए गए मूल्यों को असाइन करने के बारे में कुछ भी नहीं देखा। – ediblecode