Jon*_*ood 4 c# reflection enums
我有以下代码.我需要它来创建List的KeyValuePair<string, string>的名称和在指定枚举类型的每个枚举值的价值.
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;
}
Run Code Online (Sandbox Code Playgroud)
但是,该表达式会((int)e).ToString()生成以下错误.
无法将'TEnum'类型转换为'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;
}
Run Code Online (Sandbox Code Playgroud)
但这给了我错误:
无法将类型'System.Enum'转换为'int'
TEnum是 - 每个约束 - 一个结构.它不能保证是一个枚举.
但是,因为您在运行时强制执行该约束,所以您可以利用每个枚举实现的事实IConvertible:
foreach (IConvertible e in Enum.GetValues(typeof(TEnum)))
{
list.Add(new KeyValuePair<string, string>(
e.ToString(),
e.ToType(
Enum.GetUnderlyingType(typeof(TEnum)),
CultureInfo.CurrentCulture).ToString()));
}
Run Code Online (Sandbox Code Playgroud)
其他都有缺点的方法是:
你可以先铸造object然后再铸造int.
请注意,如果枚举的基础类型不是,则在运行时会失败int.
这可以通过在铸造dynamic之前进行铸造来克服int:
((int)(dynamic)e).ToString()
Run Code Online (Sandbox Code Playgroud)
但是,这又有一些问题:
如果枚举是类型long,ulong或者uint它将返回不正确的值.您可以通过强制转换来减少问题ulong,int但仍会返回负枚举值的无效值.
| 归档时间: |
|
| 查看次数: |
3913 次 |
| 最近记录: |