How to add extension methods to Enums

后端 未结 8 639
无人共我
无人共我 2020-12-02 13:46

I have this Enum code:

enum Duration { Day, Week, Month };

Can I add a extension methods for this Enum?

8条回答
  •  伪装坚强ぢ
    2020-12-02 14:31

    You can also add an extension method to the Enum type rather than an instance of the Enum:

    ///  Enum Extension Methods 
    ///  type of Enum 
    public class Enum where T : struct, IConvertible
    {
        public static int Count
        {
            get
            {
                if (!typeof(T).IsEnum)
                    throw new ArgumentException("T must be an enumerated type");
    
                return Enum.GetNames(typeof(T)).Length;
            }
        }
    }
    

    You can invoke the extension method above by doing:

    var result = Enum.Count;
    

    It's not a true extension method. It only works because Enum<> is a different type than System.Enum.

提交回复
热议问题