建立将T约束为枚举的泛型方法 - Create Generic method constraining T to an Enum

问题:

I'm building a function to extend the Enum.Parse concept that 我正在构建一个函数来扩展Enum.Parse概念, 安全

  • Allows a default value to be parsed in case that an Enum value is not found 若是找不到Enum值,则容许解析默认值
  • Is case insensitive 不区分大小写

So I wrote the following: 因此我写了如下内容: app

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;
}

I am getting a Error Constraint cannot be special class System.Enum . 我收到了一个错误约束,它不能是System.Enum特殊类。 函数

Fair enough, but is there a workaround to allow a Generic Enum, or am I going to have to mimic the Parse function and pass a type as an attribute, which forces the ugly boxing requirement to your code. 足够公平,可是有一种容许通用枚举的解决方法,仍是我必须模仿Parse函数并将类型做为属性传递,这迫使对代码使用难看的装箱要求。 oop

EDIT All suggestions below have been greatly appreciated, thanks. 编辑谢谢全部下面的建议。 post

Have settled on (I've left the loop to maintain case insensitivity - I am using this when parsing XML) 已经解决(我离开了循环以保持不区分大小写-解析XML时正在使用它) ui

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 defaultValue;

        foreach (T item in Enum.GetValues(typeof(T)))
        {
            if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
        }
        return defaultValue;
    }
}

EDIT: (16th Feb 2015) Julien Lebosquain has recently posted a compiler enforced type-safe generic solution in MSIL or F# below, which is well worth a look, and an upvote. 编辑: (2015年2月16日)Julien Lebosquain最近在下面的MSIL或F#中发布了由编译器强制执行的类型安全的通用解决方案 ,这很值得一看,并值得一提。 I will remove this edit if the solution bubbles further up the page. 若是解决方案在页面上冒泡,我将删除此编辑。 this


解决方案:

参考一: https://stackoom.com/question/KaE/建立将T约束为枚举的泛型方法
参考二: https://oldbug.net/q/KaE/Create-Generic-method-constraining-T-to-an-Enum
相关文章
相关标签/搜索