循环访问C#枚举的键和值
这个问题在这里已经有了答案:
Enum类具有您正在寻找的方法。
foreach(int i in Enum.GetValues(typeof(stuff)))
{
String name = Enum.GetName(typeof(stuff), i);
NewObject thing = new NewObject
{
Name = name,
Number = i
};
}
你可以使用LINQ(几乎总是):
List<NewObject> stuff = Enum.GetValues(typeof(stuffEnum)).Cast<stuffEnum>()
.Select(s => new NewObject { Name = s.ToString(), Number = (int) s })
.ToList();
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
链接地址: http://www.djcxy.com/p/91505.html