C# 枚举类型的扩展

可以将这些方法封装起来。

随机获得一个枚举

public static T RandomEnum()
    {
        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(params T[] exclude)
    {
        T[] results = Enum.GetValues(typeof(T)) as T[];

        if (exclude != null)
        {
            results = results.Except(new List(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(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;
    }

每天进步一点点。

你可能感兴趣的:(C#)