How can I use Generics to create a way of making an IEnumerable from an enum?

后端 未结 3 1963
遇见更好的自我
遇见更好的自我 2021-01-18 09:33

Given an enum like this:

public enum City {
    London    = 1,
    Liverpool  = 20,
    Leeds       = 25
}

public enum House {
    OneFloor    = 1,
    TwoF         


        
3条回答
  •  一整个雨季
    2021-01-18 09:54

    Why not:

        IEnumerable GetValues()
        {
            return Enum.GetValues(typeof (T))
                       .Cast()
                       .Select(value => new {     
                                                 value = Convert.ToInt32(value),
                                                 name = value.ToString()
                                             });
    
        }
    
    
    

    So you can use:

    var result = GetValues();
    

    If you would like to make constraint generic T as enum, because enum cannot be used as generic contraint directly, but enum inherits from interface IConvertible, believe this way is okay:

    IEnumerable GetValues() where T: struct, IConvertible
    {}
    
    
    

    To replace IEnumerable by Dictionary:

    Dictionary GetValues() where T :  struct, IConvertible
    {
        return Enum.GetValues(typeof (T)).Cast()
                   .ToDictionary(value => Convert.ToInt32(value),
                                 value => value.ToString());
    }
    

    Edit: As Magnus's comment, if you need to make sure the order of items, Dictionary is not the option. Define your own strong type would be better.

    提交回复
    热议问题