Eth*_*own 3 c# generics extension-methods enums
我为字符串添加了一些扩展方法,以便更轻松地处理一些自定义枚举.
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);
}
Run Code Online (Sandbox Code Playgroud)
注意 - 由于泛型类型约束的限制,我必须编写如上所述的方法.我很乐意使用T ToEnum(这个字符串s),其中T:Enum在拨打电话后避免演员......但是没有办法.
无论如何,我认为将这个概念扩展到返回Enum会很好吗?在方法签名可以接受各种可以为空的枚举的情况下.
public static Enum? ToEnumSafe<T>(this string s)
{
return (IsEnum<T>(s) ? (Enum)Enum.Parse(typeof(T), s) : null);
}
Run Code Online (Sandbox Code Playgroud)
但是,由于编译器错误,这是不可行的.
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>'
Run Code Online (Sandbox Code Playgroud)
我不得不承认我在这里有点困惑作为Enum?应该是合法的返回值,不是吗?我尝试了类似的东西,但最终得到了同样的错误.
public static T? ToEnumSafe<T>(this string s)
{
return (IsEnum<T>(s) ? (T)Enum.Parse(typeof(T), s) : null);
}
Run Code Online (Sandbox Code Playgroud)
我甚至决定重写方法来删除泛型,我得到更多相同的东西:
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);
}
Run Code Online (Sandbox Code Playgroud)
我在这里错过了一些非常愚蠢的东西吗?
尝试:
public static T? ToEnumSafe<T>(this string s) where T : struct
{
return (IsEnum<T>(s) ? (T?)Enum.Parse(typeof(T), s) : null);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12939 次 |
| 最近记录: |