C# 枚舉類型的擴展

可以將這些方法封裝起來。

隨機獲得一個枚舉

public static T RandomEnum<T>()
    {
        T[] results = Enum.GetValues(typeof(T)) as T[];
        Random random = new Random();
        T result = results[random.Next(0, results.Length)];
        return result;
    }

剔除exclude,再隨機獲得一個枚舉

 public static T RandomEnum<T>(params T[] exclude)
    {
        T[] results = Enum.GetValues(typeof(T)) as T[];

        if (exclude != null)
        {
            results = results.Except(new List<T>(exclude)).ToArray();
        }
        Random random = new Random();
        T result = results[random.Next(0, results.Length)];
        return result;
    }

枚舉轉字符串

(T)System.Enum.Parse(typeof(T), "")

字符串轉枚舉

 public static T ToEnum<T>(this string value, T defaultValue = default(T))
    {
        if (value == null)
            return defaultValue;

        bool found = false;
        foreach (string name in Enum.GetNames(typeof(T)))
        {
            if (value == name)
            {
                found = true;
                break;
            }
        }

        if (!found)
            return defaultValue;

        T result = (T)Enum.Parse(typeof(T), value);
        if (result == null)
            return defaultValue;

        return result;
    }

每天進步一點點。

發佈了40 篇原創文章 · 獲贊 7 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章