我正在构建一个扩展Enum.Parse概念的函数
所以我写了以下内容:
public static T GetEnumFromString<T>(string value, T defaultValue) where T : Enum
{
if (string.IsNullOrEmpty(value)) return defaultValue;
foreach (T item in Enum.GetValues(typeof(T)))
{
if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
}
return defaultValue;
}
Run Code Online (Sandbox Code Playgroud)
我得到一个Error Constraint不能是特殊类System.Enum.
很公平,但是有一个解决方法允许Generic Enum,或者我将不得不模仿该Parse函数并将类型作为属性传递,这会迫使您的代码出现丑陋的拳击要求.
编辑以下所有建议都非常感谢,谢谢.
已经解决了(我已离开循环以保持不区分大小写 - 我在解析XML时使用它)
public static class EnumUtils
{
public static T ParseEnum<T>(string value, T defaultValue) where T : struct, IConvertible
{
if (!typeof(T).IsEnum) throw new ArgumentException("T must be an enumerated type");
if (string.IsNullOrEmpty(value)) return …Run Code Online (Sandbox Code Playgroud) 给定一个通用参数TEnum,它总是一个枚举类型,有没有办法从TEnum转换为int而不用装箱/拆箱?
请参阅此示例代码.这将不必要地装箱/取消装箱.
private int Foo<TEnum>(TEnum value)
where TEnum : struct // C# does not allow enum constraint
{
return (int) (ValueType) value;
}
Run Code Online (Sandbox Code Playgroud)
上面的C#是发布模式编译到下面的IL(注意装箱和拆箱操作码):
.method public hidebysig instance int32 Foo<valuetype
.ctor ([mscorlib]System.ValueType) TEnum>(!!TEnum 'value') cil managed
{
.maxstack 8
IL_0000: ldarg.1
IL_0001: box !!TEnum
IL_0006: unbox.any [mscorlib]System.Int32
IL_000b: ret
}
Run Code Online (Sandbox Code Playgroud)
枚举转换已在SO上得到广泛处理,但我无法找到解决此特定案例的讨论.