Extension method on enumeration, not instance of enumeration

前端 未结 7 1104
耶瑟儿~
耶瑟儿~ 2020-11-29 04:28

I have an enumeration for my Things like so:

public enum Things
{
   OneThing,
   AnotherThing
}

I would like to write an extension method

7条回答
  •  清歌不尽
    2020-11-29 05:00

    Extension methods only work on instances, so it can't be done, but with some well-chosen class/method names and generics, you can produce a result that looks just as good:

    public class SelectList
    {
        // Normal SelectList properties/methods go here
    
        public static SelectList Of()
        {
            Type t = typeof(T);
            if (t.IsEnum)
            {
                var values = from Enum e in Enum.GetValues(type)
                             select new { ID = e, Name = e.ToString() };
                return new SelectList(values, "Id", "Name");
            }
            return null;
        }
    }
    

    Then you can get your select list like this:

    var list = SelectList.Of();
    

    IMO this reads a lot better than Things.ToSelectList().

提交回复
热议问题