C# - 返回枚举?来自静态扩展方法

标签 c# generics enums extension-methods

我为字符串添加了一些扩展方法,以便更轻松地处理一些自定义枚举。

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/

相关文章:

c# - 无法从程序集“Microsoft.Azure.WebJobs.Host”加载类型 'Microsoft.Azure.WebJobs.Host.Scale.ConcurrencyManager'

c# - Android 和 PC 之间的通信 (C#)

java - 如何实现通用计算器类

java - 为什么在函数式接口(interface)中使用下界

java - 为什么为非泛型方法或构造函数提供显式类型参数会编译?

java - 在枚举中声明常量

c# SqlBulkCopy - 热获取原始 sql 查询

python - 枚举后需要逗号才能正确输出要列出的值

java - 枚举<?扩展界面>

c# - 如何演示 C# 变量的存储位置,堆栈或堆