public enum Suits{Spades,Hearts,Clubs,Diamonds,NumSuits}
public void PrintAllSuits(){foreach (string name in Enum.GetNames(typeof(Suits))){System.Console.WriteLine(name);}}
顺便说一句,递增值不是枚举枚举值的好方法。您应该这样做。
我将使用Enum.GetValues(typeof(Suit))代替。
public enum Suits{Spades,Hearts,Clubs,Diamonds,NumSuits}
public void PrintAllSuits(){foreach (var suit in Enum.GetValues(typeof(Suits))){System.Console.WriteLine(suit.ToString());}}
public static List<T> GetEnumValues<T>() where T : new() {T valueType = new T();return typeof(T).GetFields().Select(fieldInfo => (T)fieldInfo.GetValue(valueType)).Distinct().ToList();}
public static List<String> GetEnumNames<T>() {return typeof (T).GetFields().Select(info => info.Name).Distinct().ToList();}
如果有人知道如何摆脱T valueType = new T(),我很乐意看到一个解决方案。
调用看起来像这样:
List<MyEnum> result = Utils.GetEnumValues<MyEnum>();
public class EnumHelper{public static T[] GetValues<T>(){Type enumType = typeof(T);
if (!enumType.IsEnum){throw new ArgumentException("Type '" + enumType.Name + "' is not an enum");}
List<T> values = new List<T>();
var fields = from field in enumType.GetFields()where field.IsLiteralselect field;
foreach (FieldInfo field in fields){object value = field.GetValue(enumType);values.Add((T)value);}
return values.ToArray();}
public static object[] GetValues(Type enumType){if (!enumType.IsEnum){throw new ArgumentException("Type '" + enumType.Name + "' is not an enum");}
List<object> values = new List<object>();
var fields = from field in enumType.GetFields()where field.IsLiteralselect field;
foreach (FieldInfo field in fields){object value = field.GetValue(enumType);values.Add(value);}
return values.ToArray();}}
public static class EnumExtensions{/// <summary>/// Gets all items for an enum value./// </summary>/// <typeparam name="T"></typeparam>/// <param name="value">The value.</param>/// <returns></returns>public static IEnumerable<T> GetAllItems<T>(this T value) where T : Enum{return (T[])Enum.GetValues(typeof (T));}}
public static class Enum<T> where T : struct, IComparable, IFormattable, IConvertible{public static IEnumerable<T> GetValues(){return (T[])Enum.GetValues(typeof(T));}
public static IEnumerable<string> GetNames(){return Enum.GetNames(typeof(T));}}
public static T[] GetEnumValues<T>() where T : struct, IComparable, IFormattable, IConvertible{if (typeof(T).BaseType != typeof(Enum)){throw new ArgumentException(string.Format("{0} is not of type System.Enum", typeof(T)));}return Enum.GetValues(typeof(T)) as T[];}
public static Dictionary<int, string> ToList<T>() where T : struct{return ((IEnumerable<T>)Enum.GetValues(typeof(T))).ToDictionary(item => Convert.ToInt32(item),item => item.ToString());}
public static Dictionary<int, string> ToList<T>() where T : struct =>((IEnumerable<T>)Enum.GetValues(typeof(T))).ToDictionary(value => Convert.ToInt32(value), value => value.ToString());