鉴于这样的枚举:
public enum City {
London = 1,
Liverpool = 20,
Leeds = 25
}
public enum House {
OneFloor = 1,
TwoFloors = 2
}
Run Code Online (Sandbox Code Playgroud)
我使用以下代码给我一个IEnumerable:
City[] values = (City[])Enum.GetValues(typeof(City));
var valuesWithNames = from value in values
select new { value = (int)value, name = value.ToString() };
Run Code Online (Sandbox Code Playgroud)
代码工作得非常好,但是我必须为很多枚举做这个.有没有办法可以创建这样做的通用方法?
此功能可能会帮助您:
public static IEnumerable<KeyValuePair<int, string>> GetValues<T>() where T : struct
{
var t = typeof(T);
if(!t.IsEnum)
throw new ArgumentException("Not an enum type");
return Enum.GetValues(t).Cast<T>().Select (x =>
new KeyValuePair<int, string>(
(int)Enum.ToObject(t, x),
x.ToString()));
}
Run Code Online (Sandbox Code Playgroud)
用法:
var values = GetValues<City>();
Run Code Online (Sandbox Code Playgroud)