我有下面的代碼。我需要它的名稱和在指定枚舉類型的每個枚舉值的價值創造KeyValuePair<string, string>
的List
。無法鑄造枚舉到INT
public static List<KeyValuePair<string, string>> GetEnumList<TEnum>() where TEnum : struct
{
if (!typeof(TEnum).IsEnum)
throw new ArgumentException("Type must be an enumeration");
List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
foreach (TEnum e in Enum.GetValues(typeof(TEnum)))
list.Add(new KeyValuePair<string, string>(e.ToString(), ((int)e).ToString()));
return list;
}
但是,表達式((int)e).ToString()
生成以下錯誤。
Cannot convert type 'TEnum' to 'int'
我只是想將一個枚舉實例轉換爲一個整數。誰能告訴我爲什麼這不起作用?
編輯:
我想這個版本:
enum Fruit : short
{
Apple,
Banana,
Orange,
Pear,
Plum,
}
void Main()
{
foreach (var x in EnumHelper.GetEnumList<Fruit>())
Console.WriteLine("{0}={1}", x.Value, x.Key);
}
public static List<KeyValuePair<string, string>> GetEnumList<TEnum>() where TEnum : struct
{
if (!typeof(TEnum).IsEnum)
throw new ArgumentException("Type must be an enumeration");
List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
foreach (TEnum e in Enum.GetValues(typeof(TEnum)))
{
list.Add(new KeyValuePair<string, string>(e.ToString(), ((int)(dynamic)e).ToString()));
}
return list;
}
但是,這給我的錯誤:
Cannot convert type 'System.Enum' to 'int'
你的'TEnum'永遠不會是'int',因爲'TEnum:struct'所以它總是一個結構 – WiiMaxx
@WiiMaxx:'struct'只是表示它是一個值類型,'int'是。 –
,但你如何從[this](http://msdn.microsoft.com/en-au/library/ah19swz4(v = vs.80).aspx)獲得'int',因爲我將結構理解爲一個簡單容器的值 – WiiMaxx