How to add extension methods to Enums

后端 未结 8 659
无人共我
无人共我 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:21

    All answers are great, but they are talking about adding extension method to a specific type of enum.

    What if you want to add a method to all enums like returning an int of current value instead of explicit casting?

    public static class EnumExtensions
    {
        public static int ToInt(this T soure) where T : IConvertible//enum
        {
            if (!typeof(T).IsEnum)
                throw new ArgumentException("T must be an enumerated type");
    
            return (int) (IConvertible) soure;
        }
    
        //ShawnFeatherly funtion (above answer) but as extention method
        public static int Count(this T soure) where T : IConvertible//enum
        {
            if (!typeof(T).IsEnum)
                throw new ArgumentException("T must be an enumerated type");
    
            return Enum.GetNames(typeof(T)).Length;
        }
    }
    

    The trick behind IConvertible is its Inheritance Hierarchy see MDSN

    Thanks to ShawnFeatherly for his answer

提交回复
热议问题