建立將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
相關文章
相關標籤/搜索