Utwórz metodę ogólną ograniczającą t do Enum

Buduję funkcję rozszerzającą Enum.Parse pojęcie, które

  • pozwala na przetworzenie wartości domyślnej w przypadku, gdy wartość Enum nie została znaleziona
  • jest niewrażliwe na wielkość liter

Więc napisałem co następuje:

public static T GetEnumFromString<T>(string value, T defaultValue) where T : Enum
{
    if (string.IsNullOrEmpty(value)) return defaultValue;
    foreach (T item in Enum.GetValues(typeof(T)))
    {
        if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
    }
    return defaultValue;
}

Otrzymuję ograniczenie błędu nie może być specjalną klasą System.Enum.

W porządku, ale czy istnieje obejście pozwalające na ogólne wyliczenie, czy będę musiał naśladować funkcję Parse i przekazać Typ jako atrybut, który wymusza brzydkie Boks wymagania do kodu.

EDIT wszystkie poniższe sugestie zostały bardzo docenione, dzięki.

Ustaliłem (opuściłem pętlę, aby zachować niewrażliwość na wielkość liter - używam tego podczas parsowania XML)

public static class EnumUtils
{
    public static T ParseEnum<T>(string value, T defaultValue) where T : struct, IConvertible
    {
        if (!typeof(T).IsEnum) throw new ArgumentException("T must be an enumerated type");
        if (string.IsNullOrEmpty(value)) return defaultValue;

        foreach (T item in Enum.GetValues(typeof(T)))
        {
            if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
        }
        return defaultValue;
    }
}

EDIT: (16th Feb 2015) Julien Lebosquain niedawno opublikował kompilator wymuszony Typ-bezpieczne rozwiązanie generyczne w MSIL lub F# poniżej, które jest warte obejrzenia, i upvote. Usunę tę edycję, jeśli rozwiązanie dalej na stronę.

Author: Vadim Ovchinnikov, 2008-09-17

20 answers

Ponieważ Enum Type implementuje interfejsIConvertible, lepsza implementacja powinna wyglądać mniej więcej tak:

public T GetEnumFromString<T>(string value) where T : struct, IConvertible
{
   if (!typeof(T).IsEnum) 
   {
      throw new ArgumentException("T must be an enumerated type");
   }

   //...
}

To nadal pozwoli na przekazywanie typów wartości implementujących IConvertible. Szanse są jednak rzadkie.

 873
Author: Vivek,
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-07-21 09:34:16

Ta funkcja jest w końcu OBSŁUGIWANA W C # 7.3!

Poniższy fragment (z próbek dotnet) pokazuje, że używa:

public static Dictionary<int, string> EnumNamedValues<T>() where T : System.Enum
{
    var result = new Dictionary<int, string>();
    var values = Enum.GetValues(typeof(T));

    foreach (int item in values)
        result.Add(item, Enum.GetName(typeof(T), item));
    return result;
}

Pamiętaj, aby ustawić wersję językową w projekcie C# na wersję 7.3.


Oryginalna odpowiedź poniżej:

Jestem spóźniony na mecz, ale potraktowałem to jako wyzwanie, aby zobaczyć, jak można to zrobić. Nie jest to możliwe w C #(lub VB.NET, ale przewiń w dół dla F#), ale jest możliwe W MSIL. Napisałem to trochę....thing

// license: http://www.apache.org/licenses/LICENSE-2.0.html
.assembly MyThing{}
.class public abstract sealed MyThing.Thing
       extends [mscorlib]System.Object
{
  .method public static !!T  GetEnumFromString<valuetype .ctor ([mscorlib]System.Enum) T>(string strValue,
                                                                                          !!T defaultValue) cil managed
  {
    .maxstack  2
    .locals init ([0] !!T temp,
                  [1] !!T return_value,
                  [2] class [mscorlib]System.Collections.IEnumerator enumerator,
                  [3] class [mscorlib]System.IDisposable disposer)
    // if(string.IsNullOrEmpty(strValue)) return defaultValue;
    ldarg strValue
    call bool [mscorlib]System.String::IsNullOrEmpty(string)
    brfalse.s HASVALUE
    br RETURNDEF         // return default it empty

    // foreach (T item in Enum.GetValues(typeof(T)))
  HASVALUE:
    // Enum.GetValues.GetEnumerator()
    ldtoken !!T
    call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)
    call class [mscorlib]System.Array [mscorlib]System.Enum::GetValues(class [mscorlib]System.Type)
    callvirt instance class [mscorlib]System.Collections.IEnumerator [mscorlib]System.Array::GetEnumerator() 
    stloc enumerator
    .try
    {
      CONDITION:
        ldloc enumerator
        callvirt instance bool [mscorlib]System.Collections.IEnumerator::MoveNext()
        brfalse.s LEAVE

      STATEMENTS:
        // T item = (T)Enumerator.Current
        ldloc enumerator
        callvirt instance object [mscorlib]System.Collections.IEnumerator::get_Current()
        unbox.any !!T
        stloc temp
        ldloca.s temp
        constrained. !!T

        // if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
        callvirt instance string [mscorlib]System.Object::ToString()
        callvirt instance string [mscorlib]System.String::ToLower()
        ldarg strValue
        callvirt instance string [mscorlib]System.String::Trim()
        callvirt instance string [mscorlib]System.String::ToLower()
        callvirt instance bool [mscorlib]System.String::Equals(string)
        brfalse.s CONDITION
        ldloc temp
        stloc return_value
        leave.s RETURNVAL

      LEAVE:
        leave.s RETURNDEF
    }
    finally
    {
        // ArrayList's Enumerator may or may not inherit from IDisposable
        ldloc enumerator
        isinst [mscorlib]System.IDisposable
        stloc.s disposer
        ldloc.s disposer
        ldnull
        ceq
        brtrue.s LEAVEFINALLY
        ldloc.s disposer
        callvirt instance void [mscorlib]System.IDisposable::Dispose()
      LEAVEFINALLY:
        endfinally
    }

  RETURNDEF:
    ldarg defaultValue
    stloc return_value

  RETURNVAL:
    ldloc return_value
    ret
  }
} 

Który generuje funkcję, która wyglądałaby tak, gdyby była poprawna w C#:

T GetEnumFromString<T>(string valueString, T defaultValue) where T : Enum

Następnie z następującym kodem C#:

using MyThing;
// stuff...
private enum MyEnum { Yes, No, Okay }
static void Main(string[] args)
{
    Thing.GetEnumFromString("No", MyEnum.Yes); // returns MyEnum.No
    Thing.GetEnumFromString("Invalid", MyEnum.Okay);  // returns MyEnum.Okay
    Thing.GetEnumFromString("AnotherInvalid", 0); // compiler error, not an Enum
}

Niestety, oznacza to, że ta część kodu jest napisana w MSIL zamiast w C#, a jedyną dodatkową korzyścią jest to, że możesz ograniczyć tę metodę za pomocą System.Enum. Jest to również trochę przykre, ponieważ jest kompilowany w osobny zespół. Nie oznacza to jednak, że musisz go wdrożyć tędy.

Przez usunięcie linii .assembly MyThing{} i wywołanie ilasm w następujący sposób:

ilasm.exe /DLL /OUTPUT=MyThing.netmodule

Dostajesz netmodule zamiast assembly.

Niestety, VS2010 (i oczywiście wcześniejsze) nie obsługuje dodawania odwołań do netmodule, co oznacza, że musisz zostawić go w 2 osobnych zestawach podczas debugowania. Jedynym sposobem, aby dodać je jako część assembly byłoby uruchomienie csc.exe yourself using the /addmodule:{files} command line argument. To nie byłoby zbyt bolesne w skrypcie MSBuild. Oczywiście, jeśli jesteś odważny lub głupi, możesz uruchomić csc samodzielnie za każdym razem. I to z pewnością staje się bardziej skomplikowane, ponieważ wiele zespołów wymaga dostępu do niego.

Więc można to zrobić w .Net. czy warto się do tego dołożyć? Cóż, chyba pozwolę ci się zdecydować.


F # rozwiązanie jako alternatywa

Extra Credit: okazuje się, że ogólne Ograniczenie enum jest możliwe w co najmniej jednym innym języku. NET poza MSIL: F#.

type MyThing =
    static member GetEnumFromString<'T when 'T :> Enum> str defaultValue: 'T =
        /// protect for null (only required in interop with C#)
        let str = if isNull str then String.Empty else str

        Enum.GetValues(typedefof<'T>)
        |> Seq.cast<_>
        |> Seq.tryFind(fun v -> String.Compare(v.ToString(), str.Trim(), true) = 0)
        |> function Some x -> x | None -> defaultValue

Ten jest łatwiejszy do utrzymania, ponieważ jest to dobrze znany język z pełną obsługą Visual Studio IDE, ale nadal potrzebujesz osobnego projektu w swoim rozwiązaniu. Jednak w naturalny sposób tworzy znacznie inny IL (kod jest bardzo różny) i opiera się na bibliotece FSharp.Core, która, podobnie jak każda inna biblioteka zewnętrzna, musi stać się częścią twojej dystrybucji.

Oto jak możesz go użyć (w zasadzie tak samo jak MSIL rozwiązanie), i aby pokazać, że poprawnie zawodzi NA inaczej synonimicznych strukturach:

// works, result is inferred to have type StringComparison
var result = MyThing.GetEnumFromString("OrdinalIgnoreCase", StringComparison.Ordinal);
// type restriction is recognized by C#, this fails at compile time
var result = MyThing.GetEnumFromString("OrdinalIgnoreCase", 42);
 439
Author: Christopher Currens,
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-05-12 20:23:26

C # ≥ 7,3

[7]} począwszy od C# 7.3 (dostępne z Visual Studio 2017 ≥ v15. 7), kod ten jest teraz całkowicie poprawny:
public static TEnum Parse<TEnum>(string value)
where TEnum : struct, Enum { ... }

C # ≤ 7.2

Możesz mieć prawdziwe wymuszone ograniczenie enum kompilatora, nadużywając dziedziczenia ograniczeń. Poniższy kod określa jednocześnie ograniczenia a class i a struct:

public abstract class EnumClassUtils<TClass>
where TClass : class
{

    public static TEnum Parse<TEnum>(string value)
    where TEnum : struct, TClass
    {
        return (TEnum) Enum.Parse(typeof(TEnum), value);
    }

}

public class EnumUtils : EnumClassUtils<Enum>
{
}

Użycie:

EnumUtils.Parse<SomeEnum>("value");

UWAGA: Jest to wyraźnie określone w specyfikacji języka C# 5.0:

Jeśli parametr typu S zależy od parametru typu T wtedy: [...] Jest ważne dla S, aby mieć typ wartości constraint i T, aby mieć typ odniesienia ograniczenie. W praktyce ogranicza to T do systemu typów.Obiekt, System.ValueType, System.Enum i dowolnego typu interfejsu.

 155
Author: Julien Lebosquain,
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-05-14 08:39:21

Edit

Na to pytanie doskonale odpowiedział Julien Lebosquain. Chciałbym również rozszerzyć jego odpowiedź o ignoreCase, defaultValue i opcjonalne argumenty, dodając TryParse i ParseOrDefault.
public abstract class ConstrainedEnumParser<TClass> where TClass : class
// value type constraint S ("TEnum") depends on reference type T ("TClass") [and on struct]
{
    // internal constructor, to prevent this class from being inherited outside this code
    internal ConstrainedEnumParser() {}
    // Parse using pragmatic/adhoc hard cast:
    //  - struct + class = enum
    //  - 'guaranteed' call from derived <System.Enum>-constrained type EnumUtils
    public static TEnum Parse<TEnum>(string value, bool ignoreCase = false) where TEnum : struct, TClass
    {
        return (TEnum)Enum.Parse(typeof(TEnum), value, ignoreCase);
    }
    public static bool TryParse<TEnum>(string value, out TEnum result, bool ignoreCase = false, TEnum defaultValue = default(TEnum)) where TEnum : struct, TClass // value type constraint S depending on T
    {
        var didParse = Enum.TryParse(value, ignoreCase, out result);
        if (didParse == false)
        {
            result = defaultValue;
        }
        return didParse;
    }
    public static TEnum ParseOrDefault<TEnum>(string value, bool ignoreCase = false, TEnum defaultValue = default(TEnum)) where TEnum : struct, TClass // value type constraint S depending on T
    {
        if (string.IsNullOrEmpty(value)) { return defaultValue; }
        TEnum result;
        if (Enum.TryParse(value, ignoreCase, out result)) { return result; }
        return defaultValue;
    }
}

public class EnumUtils: ConstrainedEnumParser<System.Enum>
// reference type constraint to any <System.Enum>
{
    // call to parse will then contain constraint to specific <System.Enum>-class
}

Przykłady użycia:

WeekDay parsedDayOrArgumentException = EnumUtils.Parse<WeekDay>("monday", ignoreCase:true);
WeekDay parsedDayOrDefault;
bool didParse = EnumUtils.TryParse<WeekDay>("clubs", out parsedDayOrDefault, ignoreCase:true);
parsedDayOrDefault = EnumUtils.ParseOrDefault<WeekDay>("friday", ignoreCase:true, defaultValue:WeekDay.Sunday);

Stare

Moje stare ulepszenia na odpowiedź Vivka za pomocą komentarzy i "nowych" zmian:

  • użyj TEnum dla jasności dla użytkowników
  • dodaj więcej interface-constraints for additional constraint-checking
  • niech TryParse uchwyt ignoreCase z istniejącym parametrem (wprowadzony w VS2010/. Net 4)
  • opcjonalnie użyj generycznego default wartość (wprowadzona w VS2005/. Net 2)
  • użyj opcjonalnych argumentów(wprowadzonych w VS2010/. Net 4) z wartościami domyślnymi, dla defaultValue i ignoreCase

W wyniku:

public static class EnumUtils
{
    public static TEnum ParseEnum<TEnum>(this string value,
                                         bool ignoreCase = true,
                                         TEnum defaultValue = default(TEnum))
        where TEnum : struct,  IComparable, IFormattable, IConvertible
    {
        if ( ! typeof(TEnum).IsEnum) { throw new ArgumentException("TEnum must be an enumerated type"); }
        if (string.IsNullOrEmpty(value)) { return defaultValue; }
        TEnum lResult;
        if (Enum.TryParse(value, ignoreCase, out lResult)) { return lResult; }
        return defaultValue;
    }
}
 29
Author: Yahoo Serious,
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:55:09

Możesz zdefiniować statyczny konstruktor dla klasy, która sprawdzi, czy typ T jest enum i rzuci wyjątek, jeśli tak nie jest. Jest to metoda wspomniana przez Jeffery ' ego Richtera w jego książce CLR via C#.

internal sealed class GenericTypeThatRequiresAnEnum<T> {
    static GenericTypeThatRequiresAnEnum() {
        if (!typeof(T).IsEnum) {
        throw new ArgumentException("T must be an enumerated type");
        }
    }
}

Następnie w metodzie parse możesz po prostu użyć Enum.Parse (typeof (T), input, true) do konwersji z string do enum. Ostatni parametr true służy do ignorowania wielkości wejścia.

 18
Author: Karg,
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
2008-09-17 15:38:07

Zmodyfikowałem próbkę przez dimarzionist. Ta wersja będzie działać tylko z Enums i nie pozwoli strukturom się przedostać.

public static T ParseEnum<T>(string enumString)
    where T : struct // enum 
    {
    if (String.IsNullOrEmpty(enumString) || !typeof(T).IsEnum)
       throw new Exception("Type given must be an Enum");
    try
    {

       return (T)Enum.Parse(typeof(T), enumString, true);
    }
    catch (Exception ex)
    {
       return default(T);
    }
}
 11
Author: Bivoauc,
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
2012-04-30 23:42:54

Starałem się nieco poprawić kod:

public T LoadEnum<T>(string value, T defaultValue = default(T)) where T : struct, IComparable, IFormattable, IConvertible
{
    if (Enum.IsDefined(typeof(T), value))
    {
        return (T)Enum.Parse(typeof(T), value, true);
    }
    return defaultValue;
}
 9
Author: Martin,
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
2013-05-07 04:12:19

Należy również wziąć pod uwagę, że od wydania C # 7.3 z ograniczeniami Enum jest wspierane po wyjęciu z pudełka bez konieczności dodatkowych sprawdzania i takich tam.

Więc idąc do przodu i biorąc pod uwagę, że zmieniłeś wersję językową swojego projektu na C# 7.3 poniższy kod będzie działał idealnie:

    private static T GetEnumFromString<T>(string value, T defaultValue) where T : Enum
    {
        // Your code goes here...
    }

Jeśli nie wiesz jak zmienić wersję językową Na C # 7.3 zobacz poniższy zrzut ekranu: Tutaj wpisz opis obrazka

Edycja 1-Wymagana Wersja Visual Studio i rozważenie ReSharper

Aby Visual Studio rozpoznało nową składnię potrzebujesz co najmniej wersji 15.7. Możesz znaleźć to również wspomniane w Uwagach do wydania firmy Microsoft, zobacz Visual Studio 2017 15.7 Release Notes . Dzięki @MohamedElshawaf za wskazanie tego ważnego pytania.

Pls również zauważyć, że w moim przypadku ReSharper 2018.1 jak pisanie tej edycji nie obsługuje jeszcze C # 7.3. Po aktywacji ReSharper zaznacza ograniczenie Enum jako błąd mówiący, że nie można użyć ' System.Array", " System.Delegat", " System.Enum', ' System.ValueType', 'object' jako parametr typu constraint . ReSharper sugeruje jako szybką poprawkę usunięcie ograniczenia "Enum" typu paramter t metody

Jeśli jednak wyłączysz ReSharper tymczasowo pod Tools - > Options -> ReSharper Ultimate - > General zobaczysz, że składnia jest całkowicie w porządku, biorąc pod uwagę, że używasz VS 15.7 lub wyższej i C# 7.3 lub wyższej.

 7
Author: baumgarb,
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-05-12 17:04:35

Mam specyficzne wymagania, w których wymagane jest użycie enum z tekstem powiązanym z wartością enum. Na przykład, gdy używam enum, aby określić typ błędu, wymagane jest opisanie szczegółów błędu.

public static class XmlEnumExtension
{
    public static string ReadXmlEnumAttribute(this Enum value)
    {
        if (value == null) throw new ArgumentNullException("value");
        var attribs = (XmlEnumAttribute[]) value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof (XmlEnumAttribute), true);
        return attribs.Length > 0 ? attribs[0].Name : value.ToString();
    }

    public static T ParseXmlEnumAttribute<T>(this string str)
    {
        foreach (T item in Enum.GetValues(typeof(T)))
        {
            var attribs = (XmlEnumAttribute[])item.GetType().GetField(item.ToString()).GetCustomAttributes(typeof(XmlEnumAttribute), true);
            if(attribs.Length > 0 && attribs[0].Name.Equals(str)) return item;
        }
        return (T)Enum.Parse(typeof(T), str, true);
    }
}

public enum MyEnum
{
    [XmlEnum("First Value")]
    One,
    [XmlEnum("Second Value")]
    Two,
    Three
}

 static void Main()
 {
    // Parsing from XmlEnum attribute
    var str = "Second Value";
    var me = str.ParseXmlEnumAttribute<MyEnum>();
    System.Console.WriteLine(me.ReadXmlEnumAttribute());
    // Parsing without XmlEnum
    str = "Three";
    me = str.ParseXmlEnumAttribute<MyEnum>();
    System.Console.WriteLine(me.ReadXmlEnumAttribute());
    me = MyEnum.One;
    System.Console.WriteLine(me.ReadXmlEnumAttribute());
}
 5
Author: Sunny Rajwadi,
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
2010-04-18 05:38:20

Mam nadzieję, że to pomoże:

public static TValue ParseEnum<TValue>(string value, TValue defaultValue)
                  where TValue : struct // enum 
{
      try
      {
            if (String.IsNullOrEmpty(value))
                  return defaultValue;
            return (TValue)Enum.Parse(typeof (TValue), value);
      }
      catch(Exception ex)
      {
            return defaultValue;
      }
}
 4
Author: dimarzionist,
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
2013-05-07 04:11:50

Co ciekawe, najwyraźniej jest to możliwe w innych językach (zarządzane C++, IL bezpośrednio).

Cytuję:

... Oba ograniczenia faktycznie wytwarzają poprawny IL i mogą być również wykorzystywane przez C#, jeśli są napisane w innym języku (możesz zadeklarować te ograniczenia w managed C++ lub w IL).

Kto wie

 3
Author: Andrew Backer,
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
2009-07-07 17:00:47

To jest moje podejście do tego. W połączeniu z odpowiedziami i MSDN

public static TEnum ParseToEnum<TEnum>(this string text) where TEnum : struct, IConvertible, IComparable, IFormattable
{
    if (string.IsNullOrEmpty(text) || !typeof(TEnum).IsEnum)
        throw new ArgumentException("TEnum must be an Enum type");

    try
    {
        var enumValue = (TEnum)Enum.Parse(typeof(TEnum), text.Trim(), true);
        return enumValue;
    }
    catch (Exception)
    {
        throw new ArgumentException(string.Format("{0} is not a member of the {1} enumeration.", text, typeof(TEnum).Name));
    }
}

MSDN Source

 3
Author: KarmaEDV,
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
2014-03-25 16:05:51

Istniejące odpowiedzi są prawdziwe od C # (powiązane z żądaniem funkcji corefx), aby umożliwić następujące czynności;

public class MyGeneric<TEnum> where TEnum : System.Enum
{ }

W czasie pisania, funkcja jest "w dyskusji" na spotkaniach rozwoju języka.

EDIT

Zgodnie z informacją nawfal jest to wprowadzone w C# 7.3.

 3
Author: DiskJunky,
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-04-12 20:35:52

Zawsze mi się to podobało (można modyfikować odpowiednio):

public static IEnumerable<TEnum> GetEnumValues()
{
  Type enumType = typeof(TEnum);

  if(!enumType.IsEnum)
    throw new ArgumentException("Type argument must be Enum type");

  Array enumValues = Enum.GetValues(enumType);
  return enumValues.Cast<TEnum>();
}
 1
Author: Jeff,
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
2010-10-05 20:04:34

Spodobało mi się rozwiązanie Christophera Currensa przy użyciu IL, ale dla tych, którzy nie chcą mieć do czynienia ze skomplikowanym biznesem włączania MSIL do procesu budowania, napisałem podobną funkcję w C#.

Pamiętaj jednak, że nie możesz używać ogólnych ograniczeń, takich jak where T : Enum, ponieważ Enum jest specjalnym typem. Dlatego muszę sprawdzić, czy dany rodzaj generyczny jest rzeczywiście enum.

Moja funkcja to:

public static T GetEnumFromString<T>(string strValue, T defaultValue)
{
    // Check if it realy enum at runtime 
    if (!typeof(T).IsEnum)
        throw new ArgumentException("Method GetEnumFromString can be used with enums only");

    if (!string.IsNullOrEmpty(strValue))
    {
        IEnumerator enumerator = Enum.GetValues(typeof(T)).GetEnumerator();
        while (enumerator.MoveNext())
        {
            T temp = (T)enumerator.Current;
            if (temp.ToString().ToLower().Equals(strValue.Trim().ToLower()))
                return temp;
        }
    }

    return defaultValue;
}
 1
Author: expert,
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
2012-04-23 01:23:29

Zamknąłem rozwiązanie Viveka w klasie użytkowej, którą możesz użyć ponownie. Należy pamiętać, że nadal należy zdefiniować ograniczenia typu "where t : struct, IConvertible"w swoim typie.

using System;

internal static class EnumEnforcer
{
    /// <summary>
    /// Makes sure that generic input parameter is of an enumerated type.
    /// </summary>
    /// <typeparam name="T">Type that should be checked.</typeparam>
    /// <param name="typeParameterName">Name of the type parameter.</param>
    /// <param name="methodName">Name of the method which accepted the parameter.</param>
    public static void EnforceIsEnum<T>(string typeParameterName, string methodName)
        where T : struct, IConvertible
    {
        if (!typeof(T).IsEnum)
        {
            string message = string.Format(
                "Generic parameter {0} in {1} method forces an enumerated type. Make sure your type parameter {0} is an enum.",
                typeParameterName,
                methodName);

            throw new ArgumentException(message);
        }
    }

    /// <summary>
    /// Makes sure that generic input parameter is of an enumerated type.
    /// </summary>
    /// <typeparam name="T">Type that should be checked.</typeparam>
    /// <param name="typeParameterName">Name of the type parameter.</param>
    /// <param name="methodName">Name of the method which accepted the parameter.</param>
    /// <param name="inputParameterName">Name of the input parameter of this page.</param>
    public static void EnforceIsEnum<T>(string typeParameterName, string methodName, string inputParameterName)
        where T : struct, IConvertible
    {
        if (!typeof(T).IsEnum)
        {
            string message = string.Format(
                "Generic parameter {0} in {1} method forces an enumerated type. Make sure your input parameter {2} is of correct type.",
                typeParameterName,
                methodName,
                inputParameterName);

            throw new ArgumentException(message);
        }
    }

    /// <summary>
    /// Makes sure that generic input parameter is of an enumerated type.
    /// </summary>
    /// <typeparam name="T">Type that should be checked.</typeparam>
    /// <param name="exceptionMessage">Message to show in case T is not an enum.</param>
    public static void EnforceIsEnum<T>(string exceptionMessage)
        where T : struct, IConvertible
    {
        if (!typeof(T).IsEnum)
        {
            throw new ArgumentException(exceptionMessage);
        }
    }
}
 1
Author: niaher,
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
2013-09-24 07:42:30

I created a extension Method to get integer value from enum spójrz na implementację metody

public static int ToInt<T>(this T soure) where T : IConvertible//enum
{
    if (typeof(T).IsEnum)
    {
        return (int) (IConvertible)soure;// the tricky part
    }
    //else
    //    throw new ArgumentException("T must be an enumerated type");
    return soure.ToInt32(CultureInfo.CurrentCulture);
}

This is usage

MemberStatusEnum.Activated.ToInt()// using extension Method
(int) MemberStatusEnum.Activated //the ordinary way
 1
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
2016-11-01 10:22:43

Jak wspomniano wcześniej w innych odpowiedziach; chociaż nie można tego wyrazić w kodzie źródłowym, można to zrobić na poziomie IL. @ Krzysiek odpowiedz pokazuje, jak IL to robi.

With Fody s Add-in ExtraConstraints.Fody istnieje bardzo prosty sposób, wraz z oprzyrządowaniem do budowania, aby to osiągnąć. Wystarczy dodać swoje pakiety nuget(Fody, ExtraConstraints.Fody) do swojego projektu i dodać ograniczenia w następujący sposób (fragment Readme z ExtraConstraints): {]}

public void MethodWithEnumConstraint<[EnumConstraint] T>() {...}

public void MethodWithTypeEnumConstraint<[EnumConstraint(typeof(ConsoleColor))] T>() {...}

I Fody doda niezbędne IL, aby ograniczenie było obecne. Zwróć również uwagę na dodatkową funkcję ograniczania delegatów:

public void MethodWithDelegateConstraint<[DelegateConstraint] T> ()
{...}

public void MethodWithTypeDelegateConstraint<[DelegateConstraint(typeof(Func<int>))] T> ()
{...}

Jeśli chodzi o liczby, warto również zwrócić uwagę na bardzo interesujące Enums.NET .

 1
Author: BatteryBackupUnit,
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-07-24 06:49:10

Jeśli jest w porządku, aby użyć bezpośredniego odlewania później, myślę, że można użyć System.Enum klasy bazowej w swojej metodzie, gdzie to konieczne. Musisz tylko ostrożnie wymienić parametry typu. Implementacja metody wygląda więc następująco:

public static class EnumUtils
{
    public static Enum GetEnumFromString(string value, Enum defaultValue)
    {
        if (string.IsNullOrEmpty(value)) return defaultValue;
        foreach (Enum item in Enum.GetValues(defaultValue.GetType()))
        {
            if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
        }
        return defaultValue;
    }
}

Wtedy możesz go użyć w następujący sposób:

var parsedOutput = (YourEnum)EnumUtils.GetEnumFromString(someString, YourEnum.DefaultValue);
 0
Author: uluorta,
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-11-23 14:39:37

W Javie, można by użyć...

    SomeClass<T extends enum> {
}
To całkiem proste.
 -3
Author: Rodney P. Barbati,
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-05-30 04:11:57