How to add extension methods to Enums

后端 未结 8 641
无人共我
无人共我 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
      }
    }
    
    0 讨论(0)
  • 2020-12-02 14:46

    Of course you can, say for example, you want to use the DescriptionAttribue on your enum values:

    using System.ComponentModel.DataAnnotations;
    
    public enum Duration 
    { 
        [Description("Eight hours")]
        Day,
    
        [Description("Five days")]
        Week,
    
        [Description("Twenty-one days")] 
        Month 
    }
    

    Now you want to be able to do something like:

    Duration duration = Duration.Week;
    var description = duration.GetDescription(); // will return "Five days"
    

    Your extension method GetDescription() can be written as follows:

    using System.ComponentModel;
    using System.Reflection;
    
    public static string GetDescription(this Enum value)
    {
        FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
        if (fieldInfo == null) return null;
        var attribute = (DescriptionAttribute)fieldInfo.GetCustomAttribute(typeof(DescriptionAttribute));
        return attribute.Description;
    }
    
    0 讨论(0)
提交回复
热议问题