我为字符串添加了一些扩展方法,以便更轻松地处理一些自定义枚举。
public static Enum ToEnum<T>(this string s)
{
return (Enum)Enum.Parse(typeof(T), s);
}
public static bool IsEnum<T>(this string s)
{
return Enum.IsDefined(typeof(T), s);
}
注意——由于泛型类型约束的限制,我必须像上面那样编写方法。我很想在调用后使用 T ToEnum(this string s) where T: Enum 来避免强制转换……但做不到。
无论如何,我认为稍微扩展这个概念以返回 Enum 会很好吗?在方法签名可以接受各种可为 null 的枚举的情况下。
public static Enum? ToEnumSafe<T>(this string s)
{
return (IsEnum<T>(s) ? (Enum)Enum.Parse(typeof(T), s) : null);
}
但是,由于编译器错误,这是不行的。
error CS0453: The type 'System.Enum' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable<T>'
我不得不承认我对 Enum 有点困惑?应该是合法的返回值,不是吗?我尝试了类似的操作,但最终遇到了同样的错误。
public static T? ToEnumSafe<T>(this string s)
{
return (IsEnum<T>(s) ? (T)Enum.Parse(typeof(T), s) : null);
}
我什至决定重写方法来删除泛型,我得到了更多相同的东西:
public static bool IsEnum(this string s, Type T)
{
return Enum.IsDefined(T, s);
}
public static Enum? ToEnumSafe(this string s, Type T)
{
return (IsEnum(s, T) ? (Enum)Enum.Parse(T, s) : null);
}
我是不是漏掉了一些非常愚蠢的东西?
最佳答案
尝试:
public static T? ToEnumSafe<T>(this string s) where T : struct
{
return (IsEnum<T>(s) ? (T?)Enum.Parse(typeof(T), s) : null);
}
关于C# - 返回枚举?来自静态扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1556952/