How to add extension methods to Enums

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

    You can create an extension for anything, even object(although that's not considered best-practice). Understand an extension method just as a public static method. You can use whatever parameter-type you like on methods.

    public static class DurationExtensions
    {
      public static int CalculateDistanceBetween(this Duration first, Duration last)
      {
        //Do something here
      }
    }
    

提交回复
热议问题