如何在C#中枚举枚举?
例如,以下代码无法编译:
public enum Suit
{
Spades,
Hearts,
Clubs,
Diamonds
}
public void EnumerateAllSuitsDemoMethod()
{
foreach (Suit suit in Suit)
{
DoSomething(suit);
}
}
它给出了以下编译时错误:
“Suit”是“type”,但与“variable”类似
它在第二个Suit关键字上失败。
如果您知道类型将是枚举,但在编译时不知道确切的类型是什么,该怎么办?
public class EnumHelper
{
public static IEnumerable<T> GetValues<T>()
{
return Enum.GetValues(typeof(T)).Cast<T>();
}
public static IEnumerable getListOfEnum(Type type)
{
MethodInfo getValuesMethod = typeof(EnumHelper).GetMethod("GetValues").MakeGenericMethod(type);
return (IEnumerable)getValuesMethod.Invoke(null, null);
}
}
getListOfEnum方法使用反射获取任何枚举类型,并返回所有枚举值的IEnumerable。
用法:
Type myType = someEnumValue.GetType();
IEnumerable resultEnumerable = getListOfEnum(myType);
foreach (var item in resultEnumerable)
{
Console.WriteLine(String.Format("Item: {0} Value: {1}",item.ToString(),(int)item));
}
我的解决方案在.NET Compact Framework(3.5)中工作,并支持编译时的类型检查:
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>();
如果您需要在构建和运行时进行速度和类型检查,则此助手方法比使用LINQ来强制转换每个元素要好:
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[];
}
您可以按如下方式使用它:
static readonly YourEnum[] _values = GetEnumValues<YourEnum>();
当然,您可以返回IEnumerable<T>,但这不会给您带来任何好处。