Jak dodać metody rozszerzeń do Enum

Mam ten kod Enum:

enum Duration { Day, Week, Month };

Czy Mogę dodać metodę rozszerzenia dla tego Enum?

 134
Author: user2110292, 2013-03-13

8 answers

Zgodnie z tą stroną:

Metody rozszerzeń umożliwiają pisanie metod dla istniejących klas w sposób, w jaki inni członkowie Twojego zespołu mogą je odkryć i używać. Biorąc pod uwagę, że enums są klasami jak każda inna, nie powinno dziwić, że możesz je rozszerzyć, na przykład:]}

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");
    }
  }
}

Myślę, że enums nie są najlepszym wyborem w ogóle, ale przynajmniej pozwala to scentralizować niektóre przełączniki / if obsługi i abstrakcyjne je trochę, aż można zrobić coś lepszego. Pamiętaj, aby sprawdzić również wartości są w zakresie.

Możesz przeczytać więcej tutaj {[3] } w Microsft MSDN.

 127
Author: One Man Crew,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-03 17:15:34

Możesz również dodać metodę rozszerzenia do typu Enum, a nie instancję 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;
        }
    }
}

Możesz wywołać powyższą metodę rozszerzenia wykonując:

var result = Enum<Duration>.Count;

To nie jest prawdziwa metoda rozszerzenia. Działa tylko dlatego, że Enum jest innym typem niż System.Enum.

 61
Author: ShawnFeatherly,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-16 21:43:54

Oczywiście możesz na przykład użyć DescriptionAttribue na swoich wartościach enum:

using System.ComponentModel.DataAnnotations;

public enum Duration 
{ 
    [Description("Eight hours")]
    Day,

    [Description("Five days")]
    Week,

    [Description("Twenty-one days")] 
    Month 
}

Teraz chcesz być w stanie zrobić coś takiego:

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

Twoją metodę rozszerzenia GetDescription() można zapisać w następujący sposób:

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;
}
 49
Author: Stacked,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-04 21:33:01

Wszystkie odpowiedzi są świetne, ale mówią o dodaniu metody rozszerzenia do określonego typu enum.

Co zrobić, jeśli chcesz dodać metodę do wszystkich enum, na przykład zwracając int bieżącej wartości zamiast jawnego odlewania?

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;
    }
}

Sztuką stojącą za IConvertible jest hierarchia dziedziczenia patrz MDSN

Podziękowania dlaShawnFeatherly za odpowiedź

 34
Author: Basheer AL-MOMANI,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-07-03 09:01:33

Możesz utworzyć rozszerzenie dla wszystkiego, nawet object (chociaż nie jest to uważane za najlepszą praktykę). Zrozum metodę rozszerzenia tak jak metodę public static. Możesz użyć dowolnego typu parametru w metodach.

public static class DurationExtensions
{
  public static int CalculateDistanceBetween(this Duration first, Duration last)
  {
    //Do something here
  }
}
 8
Author: Tim Schmelter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 11:47:17

Patrz MSDN .

public static class Extensions
{
  public static string SomeMethod(this Duration enumValue)
  {
    //Do something here
    return enumValue.ToString("D"); 
  }
}
 5
Author: LukeHennerley,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-03 16:03:38

Proste obejście.

public static class EnumExtensions
{
    public static int ToInt(this Enum payLoad) {

        return ( int ) ( IConvertible ) payLoad;

    }
}

int num = YourEnum.AItem.ToInt();
Console.WriteLine("num : ", num);
 2
Author: M. Hamza Rajput,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-05-06 02:22:19

Właśnie zrobiliśmy rozszerzenie enum dla c # https://github.com/simonmau/enum_ext

To tylko implementacja dla typesafeenum, ale działa świetnie, więc stworzyliśmy pakiet do udostępnienia-baw się z nim

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}";
    }
}

Wiem, że przykład jest trochę bezużyteczny, ale masz pomysł ;)

 0
Author: simonmau,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-08-07 14:38:30