Extension method on enumeration, not instance of enumeration

前端 未结 7 1096
耶瑟儿~
耶瑟儿~ 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 04:50

    In my opinion, this is the cleanest way. Why?

    • It works for any System.Enum
    • The extension method itself is cleaner.
    • To call it you just add new and that's a small trade off (because it has to have an instance in order to work.
    • You aren't passing null around and it literally won't compile if you try to use it with another type.

    Usage:

    (new Things()).ToSelectList()
    

    Extension Method:

    [Extension()]
    public SelectList ToSelectList(System.Enum source)
    {
        var values = from Enum e in Enum.GetValues(source.GetType)
                    select new { ID = e, Name = e.ToString() };
        return new SelectList(values, "Id", "Name");    
    }
    

提交回复
热议问题