鉴于C#enum:
public enum stuffEnum: int
{
New = 0,
Old = 1,
Fresh = 2
}
如何以一种可以在一个循环中复制键及其值的方式循环它?类似的东西:
foreach(var item in stuffEnum)
{
NewObject thing = new NewObject{
Name = item.Key,
Number = item.Value
}
}
所以最终会有3个对象,其Name属性设置为" New"," Old"," Fresh"和Number属性设置为0,1和2.
我该怎么做?
答案 0 :(得分:15)
Enum课程包含您正在寻找的方法。
foreach(int i in Enum.GetValues(typeof(stuff)))
{
String name = Enum.GetName(typeof(stuff), i);
NewObject thing = new NewObject
{
Name = name,
Number = i
};
}
答案 1 :(得分:7)
您可以使用LINQ(几乎总是如此):
List<NewObject> stuff = Enum.GetValues(typeof(stuffEnum)).Cast<stuffEnum>()
.Select(s => new NewObject { Name = s.ToString(), Number = (int) s })
.ToList();
答案 2 :(得分:3)
foreach (var enumValue in Enum.GetValues(typeof(StuffEnum)))
{
Console.WriteLine("Name: {0}, Value: {1}", enumValue, (int)enumValue);
}
结果
Name: New, Value: 0
Name: Old, Value: 1
Name: Fresh, Value: 2