/ / c # "Enum" विधि पर और "enum" पैरामीटर - c #, enums

सी # "एनम" विधि और "enum" पैरामीटर पर - सी #, enums

यह google के लिए एक मुश्किल सवाल है!

मेरे पास एक विस्तार विधि है जो एक पैरामीटर के रूप में "एनम" लेता है।

    public static T GetEntry<T>(this Dictionary<Enum, string> dictionary, Enum key)
{
string val;
if (dictionary.TryGetValue(key, out val))
{
return (T)Convert.ChangeType(val, typeof(T));
}
return default(T);
}

लेकिन जब मैं इसे घोषित एनम के साथ उपयोग करने की कोशिश करता हूं तो संकलक विस्तार विधि नहीं ढूंढ सकता है

Dictionary<CmdAttr, String> Attributes;
cmd.CommandText.Attributes.GetEntry<double>(CommandText.CmdAttr.X);

किसी भी विचार के रूप में इस काम को बनाने के लिए कैसे शब्दकोश घोषित करने के अलावा अन्य

Dictionary<Enum, String> Attributes

कौन सा काम करता है लेकिन घोषित एनुम होने में किस तरह की हार?

बहुत धन्यवाद

उत्तर:

उत्तर № 1 के लिए 1

आप इसे ठीक उसी तरह से कर सकते हैं जैसे आप करना चाहते हैं, क्योंकि व्यक्तिगत एनम उप-वर्ग नहीं हैं Enum। लेकिन यद्यपि यह कोड isn "t as much as you" d like, it’s’s शायद ही बदसूरत है, और यह आप के रूप में काम करता है "d:

// MyTestEnum.cs

enum MyTestEnum
{
First,
Second,
Third
}

// Extensions.cs

static class Extensions
{
public static TResult GetEntry<TEnum, TResult>(this Dictionary<TEnum, string> dictionary, TEnum key)
{
string value;
if (dictionary.TryGetValue(key, out value))
{
return (TResult)Convert.ChangeType(value, typeof(TResult));
}
return default(TResult);
}
}

// most likely Program.cs

void Main()
{
Dictionary<MyTestEnum, string> attributes = new Dictionary<MyTestEnum, string>();
attributes.Add(MyTestEnum.First, "1.23");

// *** here"s the actual call to the extension method ***
var result = attributes.GetEntry<MyTestEnum, double>(MyTestEnum.First);

Console.WriteLine(result);
}

उत्तर № 2 के लिए -1

आप क्या करना चाहते हैं (निम्नलिखित मान्य नहीं है # कोड):

public static T GetEntry<T,U>(this Dictionary<U, string> dictionary, U key) where U : Enum
{
// your code
}

यह संकलित नहीं होगा (बाधा को विशेष वर्ग "एनम" नहीं कहा जा सकता है)। इसलिए आपको विकल्प तलाशने होंगे। कुछ अच्छे जवाब हैं इस सवाल। सबसे आसान तरीका उपयोग करना होगा where U : struct, IConvertible