public List<string> GetValues(Type enumType)
{
if(!typeof(Enum).IsAssignableFrom(enumType))
throw new ArgumentException("enumType should describe enum");
var names = Enum.GetNames(enumType).Cast<object>();
var values = Enum.GetValues(enumType).Cast<int>();
return names.Zip(values, (name, value) => string.Format("Value {0} Name {1}", value, name))
.ToList();
}
现在如果你和
GetValues(typeof(MyEnum)).ForEach(Console.WriteLine);
将打印:
Value 5 Name A
Value 6 Name B
Value 8 Name C
非 LINQ 版本:
public List<string> GetValues(Type enumType)
{
if(!typeof(Enum).IsAssignableFrom(enumType))
throw new ArgumentException("enumType should describe enum");
Array names = Enum.GetNames(enumType);
Array values = Enum.GetValues(enumType);
List<string> result = new List<string>(capacity:names.Length);
for (int i = 0; i < names.Length; i++)
{
result.Add(string.Format("Value {0} Name {1}",
(int)values.GetValue(i), names.GetValue(i)));
}
return result;
}