Extension method on enumeration, not instance of enumeration

前端 未结 7 1093
耶瑟儿~
耶瑟儿~ 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条回答
  •  -上瘾入骨i
    2020-11-29 05:08

    I use 'Type' instead of 'Enum' to add extension. Then I can get any type of list back from the method. Here it returns string values:

        public static string[] AllDescription(this Type enumType)
        {
            if (!enumType.IsEnum) return null;
    
            var list = new List();
            var values = Enum.GetValues(enumType);
    
            foreach (var item in values)
            {
                // add any combination of information to list here:
                list.Add(string.Format("{0}", item));
    
                //this one gets the values from the [Description] Attribute that I usually use to fill drop downs
                //list.Add(((Enum) item).GetDescription());
            }
    
            return list.ToArray();
        }
    

    Later I could use this syntax to get what I want:

    var listOfThings = typeof (Things).AllDescription();
    

提交回复
热议问题