How to add extension methods to Enums

后端 未结 8 640
无人共我
无人共我 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<T>(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<T>(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

    0 讨论(0)
  • 2020-12-02 14:26

    According to this site:

    Extension methods provide a way to write methods for existing classes in a way other people on your team might actually discover and use. Given that enums are classes like any other it shouldn’t be too surprising that you can extend them, like:

    enum Duration { Day, Week, Month };
    
    static class DurationExtensions 
    {
      public static DateTime From(this Duration duration, DateTime dateTime) 
      {
        switch (duration) 
        {
          case Day:   return dateTime.AddDays(1);
          case Week:  return dateTime.AddDays(7);
          case Month: return dateTime.AddMonths(1);
          default:    throw new ArgumentOutOfRangeException("duration");
        }
      }
    }
    

    I think enums are not the best choice in general but at least this lets you centralize some of the switch/if handling and abstract them away a bit until you can do something better. Remember to check the values are in range too.

    You can read more here at Microsft MSDN.

    0 讨论(0)
  • 2020-12-02 14:31

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

    /// <summary> Enum Extension Methods </summary>
    /// <typeparam name="T"> type of Enum </typeparam>
    public class Enum<T> 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<Duration>.Count;
    

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

    0 讨论(0)
  • 2020-12-02 14:33

    See MSDN.

    public static class Extensions
    {
      public static string SomeMethod(this Duration enumValue)
      {
        //Do something here
        return enumValue.ToString("D"); 
      }
    }
    
    0 讨论(0)
  • 2020-12-02 14:34

    A Simple workaround.

    public static class EnumExtensions
    {
        public static int ToInt(this Enum payLoad) {
    
            return ( int ) ( IConvertible ) payLoad;
    
        }
    }
    
    int num = YourEnum.AItem.ToInt();
    Console.WriteLine("num : ", num);
    
    0 讨论(0)
  • 2020-12-02 14:35

    we have just made an enum extension for c# https://github.com/simonmau/enum_ext

    It's just a implementation for the typesafeenum, but it works great so we made a package to share - have fun with it

    public sealed class Weekday : TypeSafeNameEnum<Weekday, int>
    {
        public static readonly Weekday Monday = new Weekday(1, "--Monday--");
        public static readonly Weekday Tuesday = new Weekday(2, "--Tuesday--");
        public static readonly Weekday Wednesday = new Weekday(3, "--Wednesday--");
        ....
    
        private Weekday(int id, string name) : base(id, name)
        {
        }
    
        public string AppendName(string input)
        {
            return $"{Name} {input}";
        }
    }
    

    I know the example is kind of useless, but you get the idea ;)

    0 讨论(0)
提交回复
热议问题