C# 枚举类型的扩展

来源:互联网 发布:linux网络工程师培训 编辑:程序博客网 时间:2024/05/16 18:04

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

随机获得一个枚举

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

每天进步一点点。

0 0
原创粉丝点击