如何在C#中枚举枚举?
例如,以下代码无法编译:
public enum Suit
{
Spades,
Hearts,
Clubs,
Diamonds
}
public void EnumerateAllSuitsDemoMethod()
{
foreach (Suit suit in Suit)
{
DoSomething(suit);
}
}
它给出了以下编译时错误:
“Suit”是“type”,但与“variable”类似
它在第二个Suit关键字上失败。
我使用ToString(),然后拆分并解析flags中的spit数组。
[Flags]
public enum ABC {
a = 1,
b = 2,
c = 4
};
public IEnumerable<ABC> Getselected (ABC flags)
{
var values = flags.ToString().Split(',');
var enums = values.Select(x => (ABC)Enum.Parse(typeof(ABC), x.Trim()));
return enums;
}
ABC temp= ABC.a | ABC.b;
var list = getSelected (temp);
foreach (var item in list)
{
Console.WriteLine(item.ToString() + " ID=" + (int)item);
}
如果您知道类型将是枚举,但在编译时不知道确切的类型是什么,该怎么办?
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));
}
我想这对你有帮助。
public class Program
{
public static List<T> GetEnamList<T>()
{
var enums = Enum.GetValues(typeof(T)).Cast<T>().Select(v => v).ToList();
return enums;
}
private void LoadEnumList()
{
List<DayofWeek> dayofweeks = GetEnamList<DayofWeek>();
foreach (var item in dayofweeks)
{
dayofweeks.Add(item);
}
}
}
public enum DayofWeek
{
Monday,
Tuesday,
Wensday,
Thursday,
Friday,
Sturday,
Sunday
}