如何使用Generics创建一种从枚举中创建IEnumerable的方法?

Sam*_*tar 5 c#

鉴于这样的枚举:

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)

代码工作得非常好,但是我必须为很多枚举做这个.有没有办法可以创建这样做的通用方法?

Mag*_*nus 2

此功能可能会帮助您:

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)