我正在构建一个扩展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) 我有一个泛型类型,应该用Enum类型指定(实际上,它是几个指定枚举之一,但我会满足System.Enum).
当然编译器会在代码中发挥作用:
class Generic<T> where T : Enum {}
Run Code Online (Sandbox Code Playgroud)
用"约束不能特殊的类'System.Enum'"例外.
到目前为止我唯一能够提出的解决方案是使用静态类型初始值设定项来检查类型参数,如果事实上不是枚举,则抛出异常,如下所示:
class Generic<T>
{
static Generic()
{
if (typeof(T).BaseType != typeof(Enum))
throw new Exception("Invalid Generic Argument");
}
}
Run Code Online (Sandbox Code Playgroud)
至少给了我运行时安全性,它不会与非枚举参数一起使用.然而,这感觉有点hacky,所以是否有更好的方法来实现这一点,理想情况下使用编译时构造?