다음 코드가 있습니다. List
이 KeyValuePair<string, string>
이고 지정한 열거 형의 각 열거 형 값의 이름과 값이 필요합니다.Enum을 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 인스턴스를 캐스팅하려고합니다. 아무도 왜 이것이 작동하지 않습니다 말해 줄래?
편집 :
내가이 버전을 시도 :
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'가 아니기 때문에'where TEnum : struct'는 항상 구조체가 될 것입니다. – WiiMaxx
@WiiMaxx :'struct'는 int 타입의 값 타입을 의미합니다. –
하지만 구조체를 단순한 것으로 이해했기 때문에 [int] (http://msdn.microsoft.com/en-au/library/ah19swz4(v=80) .aspx)에서 어떻게 얻을 수 있습니까? 값을위한 컨테이너 – WiiMaxx