如何使用泛型创建作出了IEnumerable由枚举的方法吗? [英] How can I use Generics to create a way of making an IEnumerable from an enum?
本文介绍了如何使用泛型创建作出了IEnumerable由枚举的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
由于像这样的枚举:
public enum City {
London = 1,
Liverpool = 20,
Leeds = 25
}
public enum House {
OneFloor = 1,
TwoFloors = 2
}
我使用下面的代码给我一个IEnumerable
I am using the following code to give me an IEnumerable:
City[] values = (City[])Enum.GetValues(typeof(City));
var valuesWithNames = from value in values
select new { value = (int)value, name = value.ToString() };
代码工作非常好,但是我必须为相当多的枚举做到这一点。有没有一种方法我可以创建这样的通用方法
The code works very good however I have to do this for quite a lot of enums. Is there a way I could create a generic way of doing this?
推荐答案
此功能可以帮助你:
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()));
}
用法:
Usage:
var values = GetValues<City>();
这篇关于如何使用泛型创建作出了IEnumerable由枚举的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文