T를 Enum으로 제한하는 제네릭 메서드 만들기


1188

Enum.Parse개념 을 확장하는 기능을 만들고 있습니다.

  • 열거 형 값을 찾을 수없는 경우 기본값을 구문 분석 할 수 있습니다.
  • 대소 문자를 구분하지 않습니다

그래서 나는 다음과 같이 썼다.

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

오류가 발생했습니다. 제약 조건은 특수 클래스가 될 수 없습니다 System.Enum.

충분히 공평하지만 Generic Enum을 허용하는 해결 방법이 있습니까? 아니면 Parse함수 를 모방하고 유형을 속성으로 전달해야합니다.

편집 아래의 모든 제안은 대단히 감사합니다.

해결했습니다 (대소 문자를 구분하지 않기 위해 루프를 떠났습니다. 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;
    }
}

편집 : (2015 년 2 월 16 일) Julien Lebosquain은 최근 MSIL 또는 F #에 컴파일러 적용 형식 안전 일반 솔루션을 게시 했습니다 . 솔루션에서 페이지가 더 위로 올라가면이 편집 내용을 제거하겠습니다.


10
어쩌면 ToLower () 대신 ToUpperInvariant () 를 사용해야합니다 .
— Max Galkin

31
@ Shimmy : 값 유형을 확장 메소드에 전달하자마자 사본을 작성하고 있으므로 상태를 변경할 수 없습니다.
— 가로 Yeriazarian

4
그것이 오래된 스레드라는 것을 알고, 그것들이 변경되었는지 알지 못하지만, 확장 메소드는 값 유형에 대해 잘 작동하지만 항상 의미가 없을 수도 있지만 "public static TimeSpan Seconds (this int x) { "Wait.For (5.Seconds ()) ..."의 구문을 활성화하려면 TimeSpan.FromSeconds (x);} "를 반환
— Jens

6
이 질문의 일부가 아니었다 실현,하지만 당신은 StringComparison.InvariantCultureIgnoreCase와 String.Equals를 사용하여 foreach 루프 로직을 개선 할 수
— Firestrand

답변:


1006

EnumType은 IConvertible인터페이스를 구현 하므로 더 나은 구현은 다음과 같아야합니다.

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

   //...
}

이것은 구현하는 값 유형의 전달을 여전히 허용합니다 IConvertible. 기회는 드물다.


2
제네릭은 .NET 2.0부터 사용할 수 있습니다. 따라서 vb 2005에서도 사용할 수 있습니다.
— Vivek

46
글쎄, 당신은이 경로 ... 사용 아래로 이동하도록 선택하는 경우가 훨씬 더 후, 제한 할 "클래스를 TestClass에 <T> 여기서 T : 구조체에서 IComparable, IFormattable, IConvertible"
— 리카르도 Nolde

106
또 다른 제안은 식별자 TEnum으로 제네릭 형식을 정의하는 것입니다. 따라서 : 공개 TEnum GetEnumFromString <TEnum> (문자열 값) 여기서 TEnum : struct, IConvertible, IComparible, IFormattable {}
— Lisa

11
거의 모든 내장 값 유형이 해당 인터페이스를 모두 구현하기 때문에 다른 인터페이스를 포함하면 많은 이점을 얻을 수 없습니다. 이것은 확장 기능이 모든 객체를 감염시키는 바이러스와 같다는 사실을 제외하고 열거 형을 조작하는 데 매우 유용한 일반 확장 방법의 제약 조건에 특히 해당됩니다. IConvertable은 적어도 상당히 좁 힙니다.
— russbishop

2
@ Samamam : 게시 할 때이 스레드는 6 세 반이었고 정확했습니다. 답변에서 컴파일 타임을 확인하지 않았습니다. 그런 지 3 일 후, 6 년 후, 당신은 당신의 소원을 얻었습니다-Julien Lebosquain의 포스트를 아래에서보십시오.
— David I. McIntosh

662

이 기능은 C # 7.3에서 지원됩니다!

다음 스 니펫 ( dotnet 샘플에서 )은 방법을 보여줍니다.

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

C # 프로젝트의 언어 버전을 버전 7.3으로 설정하십시오.


아래의 원래 답변 :

나는 게임에 늦었지만 그것을 어떻게 할 수 있는지 보는 도전으로 받아 들였다. C # (또는 VB.NET에서는 불가능 하지만 F #에서는 아래로 스크롤)에서는 불가능 하지만 MSIL 에서는 가능합니다 . 나는이 작은 것을 썼다.…

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

어떤 함수 생성하는 것 이 유효 C #을한다면, 다음과 같이를 :

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

그런 다음 다음 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
}

불행히도, 이것은 코드의이 부분을 C # 대신 MSIL로 작성했음을 의미하며,이 방법을로 제한 할 수 있다는 이점이 있습니다 System.Enum. 또한 별도의 어셈블리로 컴파일되기 때문에 일종의 윙윙 거리는 소리입니다. 그러나 그런 식으로 배포해야한다는 의미는 아닙니다.

라인을 제거하고 .assembly MyThing{}다음과 같이 일람을 불러 냄.

ilasm.exe /DLL /OUTPUT=MyThing.netmodule

어셈블리 대신 netmodule을 얻습니다.

불행히도 VS2010 (및 이전 버전)은 netmodule 참조 추가를 지원하지 않으므로 디버깅 할 때 2 개의 별도 어셈블리에 남겨 두어야합니다. 어셈블리의 일부로 추가 할 수있는 유일한 방법은 /addmodule:{files}명령 줄 인수를 사용하여 csc.exe를 직접 실행하는 것 입니다. 너무 아니야MSBuild 스크립트에서는 고통스럽지 . 물론 용감하거나 어리석은 경우 매번 수동으로 csc를 실행할 수 있습니다. 그리고 여러 어셈블리에 액세스해야하기 때문에 확실히 더 복잡해집니다.

따라서 .Net에서 수행 할 수 있습니다. 추가 노력의 가치가 있습니까? 음, 그 결정을 내릴 수있을 것 같아요.


대안으로 F # 솔루션

추가 크레딧 : enumMSIL 이외의 다른 하나 이상의 .NET 언어에서는 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

이것은 Visual Studio IDE를 완벽하게 지원하는 잘 알려진 언어이기 때문에 유지 관리하기가 쉽지만 솔루션에 별도의 프로젝트가 필요합니다. 그러나 자연스럽게 상당히 다른 IL을 생성하고 (코드 는 매우 다름)FSharp.Core 다른 외부 라이브러리와 마찬가지로 배포의 일부가되어야 라이브러리에 합니다.

다음은 기본적으로 MSIL 솔루션과 동일하게 사용하고 동의어 구조에서 올바르게 실패하는 방법을 보여줍니다.

// 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);

67
예, 매우 하드 코어입니다. 나는 IL 코드, 수있는 사람에 대한 존경이 그리고 우리 중 많은 사람은 여전히 애플리케이션, 비즈니스 규칙, UI의 구성 요소 라이브러리, 등 아래 낮은 수준 인 것으로보고 수준 - 특징은 높은 언어 수준에서 지원하는 방법을 알고를 .
— TonyG

13
내가 정말로 알고 싶은 것은 C # 팀이 MSIL에서 이미 지원하기 때문에 C # 팀이 아직 이것을 허용하지 않은 이유입니다.
— MgSam

25
@MgSam- Eric Lippert에서 :There's no particularly unusual reason why not; we have lots of other things to do, limited budgets, and this one has never made it past the "wouldn't this be nice?" discussion in the language design team.
— Christopher Currens

5
@LordofScripts : 나는 이유는이 제약 클래스 이후 있다는 것을 생각 T에이 System.Enum모든 것을 할 수 없을 것이라고 T예상하는 사람들을, C #의 저자들이 아니라 모두를 금지 할 수 있습니다 생각. C #이 System.Enum제약 조건의 특수 처리를 단순히 무시했기 때문에 결정이 불행한 것으로 생각합니다 . HasAnyFlags<T>(this T it, T other)확장 방법이 Enum.HasFlag(Enum)인수 보다 빠르며 인수를 확인한 확장 메서드 를 작성할 수 있었을 것 입니다.
— supercat

9
내가 여기서 끝나지 않은 프로젝트를 본 적이 없다고 생각합니다. C # 6은 110 %의 구문 설탕이며, 이것이 들어오지 않습니까? 쓰레기를 잘라
— Michael Blackburn

214

C # ≥ 7.3

C # 7.3 (Visual Studio 2017 ≥ v15.7에서 사용 가능)부터이 코드는 이제 완전히 유효합니다.

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

C # ≤ 7.2

제약 조건 상속을 남용하여 실제 컴파일러에서 열거 형 제약 조건을 적용 할 수 있습니다. 다음 코드는 a class와 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>
{
}

용법:

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

참고 : 이것은 C # 5.0 언어 사양에 구체적으로 설명되어 있습니다.

유형 매개 변수 S가 유형 매개 변수 T에 의존하는 경우 : [...] S가 값 유형 제한 조건을 갖고 T가 참조 유형 제한 조건을 갖는 것이 유효합니다. 사실상 이것은 T를 System.Object, System.ValueType, System.Enum 유형 및 모든 인터페이스 유형으로 제한합니다.


7
@ DavidI.McIntosh EnumClassUtils<System.Enum>는 T를 System.Enum모든 파생 유형 으로 제한하기에 충분합니다 . struct에 Parse다음 실제 열거 형에 추가를 제한합니다. Enum특정 시점 으로 제한해야합니다 . 그렇게하려면 클래스가 중첩되어야합니다. gist.github.com/MrJul/7da12f5f2d6c69f03d79
— Julien Lebosquain

7
분명히, 내 의견 "쾌적하지 않다"는 귀하의 솔루션에 대한 의견이 아닙니다. 정말 아름다운 해킹입니다. MS가 우리에게 그러한 복잡한 해킹을 사용하도록 강요하는 것은 단지 "즐겁지 않다".
— David I. McIntosh

2
확장 방법에도 사용할 수있는 방법이 있습니까?
— Mord Zuber

3
where TClass : class여기서 제약 조건 은 무엇입니까 ?
— tsemer

2
@Trinkyoenum DefinitelyNotAnInt : byte { Realize, That, I, Am, Not, An, Int } enum AlsoNotAnInt : long { Well, Bummer }
— M.Stramm

30

편집하다

Julien Lebosquain이이 질문에 대답했습니다 . 나는 또한 자신과 대답 확장하고자 ignoreCase, defaultValue추가하는 동안, 그리고 선택적 인수를 TryParse하고 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
}

사용 예 :

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

낡은

의견과 '새로운'개발을 사용하여 Vivek의 답변 에 대한 나의 오래된 개선 사항 :

  • 사용하다 TEnum 사용자에 대한 명확성을 위해
  • 추가적인 제약 조건 검사를위한 인터페이스 제약 조건 추가
  • 기존 매개 변수로 TryParse처리 하자 ignoreCase(VS2010 / .Net 4에 도입 됨)
  • 선택적으로 일반 default값을 사용하십시오 (VS2005 / .Net 2에서 도입 됨)
  • 사용 선택적 인수 에 대한 기본 값 (VS2010 / 닷넷 4 도입을) defaultValue과ignoreCase

를 야기하는:

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

18

T 타입이 열거 형인지 확인하고 그렇지 않은 경우 예외를 throw하는 클래스에 대한 정적 생성자를 정의 할 수 있습니다. 이것은 Jeffery Richter가 그의 책 CLR에서 C #을 통해 언급 한 방법입니다.

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

그런 다음 구문 분석 방법에서 Enum.Parse (typeof (T), input, true)를 사용하여 문자열에서 열거 형으로 변환 할 수 있습니다. 마지막 true 매개 변수는 입력 대소 문자를 무시하기위한 것입니다.


1
이것은 일반적인 클래스에는 좋은 옵션이지만 일반적인 방법에는 도움이되지 않습니다.
— McGarnagle

또한 이것은 컴파일 타임에도 적용되지 않으며 Enum T생성자가 실행될 때 비 제공을 알면됩니다 . 인스턴스 생성자를 기다리는 것보다 훨씬 좋습니다.
— jrh

15

또한 Enum 제약 조건을 사용하는 C # 7.3 릴리스가 추가 검사 및 작업을 수행하지 않고도 기본적으로 지원된다는 점도 고려해야합니다.

앞으로 프로젝트의 언어 버전을 C # 7.3으로 변경하면 다음 코드가 완벽하게 작동합니다.

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

언어 버전을 C # 7.3으로 변경하는 방법을 모르는 경우 다음 스크린 샷을 참조하십시오. 여기에 이미지 설명을 입력하십시오

편집 1-필수 Visual Studio 버전 및 ReSharper 고려

Visual Studio에서 새 구문을 인식하려면 버전 15.7 이상이 필요합니다. Microsoft 릴리스 정보에서도 언급 된 내용은 Visual Studio 2017 15.7 릴리스 정보를 참조하십시오 . 이 유효한 질문을 지적 해 주신 @MohamedElshawaf에게 감사드립니다.

Pls는 필자의 경우 ReSharper 2018.1을 작성하는 시점 에서이 편집은 아직 C # 7.3을 지원하지 않습니다. ReSharper를 활성화하면 'System.Array', 'System.Delegate', 'System.Enum', 'System.ValueType', 'object'를 유형 매개 변수 제약 조건으로 사용할 수 없다는 오류로 Enum 제약 조건이 강조 표시됩니다 . ReSharper는 메소드 매개 변수 T의 'Enum'제한 조건 을 제거 하는 빠른 수정 사항으로 제안합니다.

그러나 도구-> 옵션-> ReSharper Ultimate-> 일반 에서 ReSharper를 일시적으로 끄면 VS 15.7 이상 및 C # 7.3 이상을 사용하면 구문이 완벽하게 나타납니다.


1
어떤 VS 버전을 사용하고 있습니까?
— mshwf

1
@MohamedElshawaf C # 7.3에 대한 지원이 포함 된 버전 15.7이라고 생각합니다.
— Patrick Roberts

1
유형 매개 변수로 자신을 where T : struct, Enum전달하지 않으 려면을 작성하는 것이 좋습니다 System.Enum.
— Mariusz Pawelski

@MariuszPawelski처럼 내가 쓴다 struct, Enum. 나의 근거는 여기 에 대한 답변과 의견에 설명되어 있습니다 .
— Stephen Kennedy

ReSharper 정보가 정말 도움이되었습니다. 최신 미리보기 버전은이 기능을 지원합니다.
— DalSoft

11

나는 dimarzionist에 의해 샘플을 수정했습니다. 이 버전은 Enum 과만 작동하며 구조체가 통과하지 못하게합니다.

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

13
실패하면 기본값을 반환하지 않습니다. Enum.Parse와 마찬가지로 예외가 전파되도록했습니다. 대신 TryParse를 사용하여 bool을 반환하고 out 매개 변수를 사용하여 결과를 반환하십시오.
— Mark Simpson

1
OP는 대소 문자를 구분하지 않기를 원하지만 그렇지 않습니다.
— Konrad Morawski

9

코드를 약간 개선하려고했습니다.

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

1
defaultValue.ToString("D", System.Globalization.NumberFormatInfo.CurrentInfo)어떤 유형의 열거 형인지 모르는 경우에도 객체가 열거 형인 경우에도 호출 할 수 있기 때문에 허용되는 답변보다 낫습니다 .
— styfle

1
그러나 사전 점검으로 IsDefined사건이 무감각을 망칠 것입니다. 달리 Parse, IsDefined더없는 ignoreCase인수를, 그리고 MSDN 그것은 단지 정확한 대소 문자와 일치 말했다 .
— Nyerguds

5

열거 형 값과 관련된 텍스트와 함께 열거 형을 사용해야하는 특정 요구 사항이 있습니다. 예를 들어 열거 형을 사용하여 오류 유형을 지정하면 오류 세부 정보를 설명해야합니다.

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

4

이것이 도움이되기를 바랍니다.

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

1
대소 문자를 구분하지 않으려면 다음으로 대체하십시오 return (TValue)Enum.Parse(typeof (TValue), value);.return (TValue)Enum.Parse(typeof (TValue), value, true);
— Paulo Santos

3

흥미롭게도 다른 언어에서도 가능합니다. (Managed C ++, IL 직접)에서 가능합니다.

인용 :

... 두 제약 조건은 실제로 유효한 IL을 생성하며 다른 언어로 작성된 경우 C #에서도 사용할 수 있습니다 (관리되는 C ++ 또는 IL에서 이러한 제약 조건을 선언 할 수 있음).

누가 알아


2
C ++ 용 Managed Extensions는 제네릭을 지원하지 않습니다. C ++ / CLI를 의미한다고 생각합니다.
— 벤 Voigt

3

이게 내 취향이다. 답변과 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 소스


2
이것은 실제로 의미가 없습니다. 경우 TEnum실제로 열거 형이지만 text빈 문자열입니다 당신은 내려면 ArgumentException이 경우에도 "TEnum이 열거 유형이어야합니다"라고.
— Nick

3

기존 답변은 C # <= 7.2 기준입니다. 그러나 C # 언어 기능 요청 ( corefx 기능 요청과 연결됨 )이있어 다음을 허용합니다.

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

글을 쓰는 시점에서이 기능은 언어 개발 회의에서 "토론 중"입니다.

편집하다

당으로 nawfal 의 정보를 원하시면,이는 C #에서 소개되고 7.3 .


1
흥미로운 토론 감사합니다. 아직 돌에 아무것도 설정되지 않았습니다.
— johnc

1
@ johnc, 매우 사실이지만 메모할만한 가치 가 있으며 자주 묻는 기능입니다. 그것에 대한 공정한 배당률.
— DiskJunky

1
이것은 C # 7.3에서오고있다 : docs.microsoft.com/en-us/visualstudio/releasenotes/... . :)
— nawfal

1

나는 항상 이것을 좋아했다 (적절하게 수정 할 수 있음) :

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

나는 IL을 사용하는 Christopher Currens의 솔루션을 좋아했지만 MSIL을 빌드 프로세스에 포함시키는 까다로운 비즈니스를 다루고 싶지 않은 사람들을 위해 비슷한 기능을 C #으로 작성했습니다.

다음과 같은 일반적인 제한을 사용할 수는 없습니다. where T : EnumEnum은 특수 유형이므로 . 따라서 주어진 제네릭 형식이 실제로 열거 형인지 확인해야합니다.

내 기능은 다음과 같습니다

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

Vivek의 솔루션을 재사용 할 수있는 유틸리티 클래스로 캡슐화했습니다. 유형에 대한 유형 제한 조건을 "여기서 T : struct, IConvertible"로 정의해야합니다.

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

to get integer value from enum 메소드 구현을 살펴 보는 확장 메소드를 작성했습니다.

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

이것은 사용법입니다

MemberStatusEnum.Activated.ToInt()// using extension Method
(int) MemberStatusEnum.Activated //the ordinary way

아마도 효과가 있지만 질문과 거의 관련이 없습니다.
— quetzalcoatl

1

이전에 다른 답변에서 언급했듯이; 소스 코드로 표현할 수 없지만 실제로는 IL 레벨에서 수행 할 수 있습니다. @Christopher Currens 답변 은 IL이 어떻게하는지 보여줍니다.

Fody s Add-In ExtraConstraints.Fody를 사용하면 빌드 툴링으로 완성되는 매우 간단한 방법이 있습니다. 너겟 패키지 ( Fody, ExtraConstraints.Fody)를 프로젝트에 추가하고 다음과 같이 제약 조건을 추가하십시오 (ExtraConstraints 추가 정보에서 발췌).

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

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

Fody는 구속 조건이 존재하는 데 필요한 IL을 추가합니다. 또한 제한 위임의 추가 기능에 유의하십시오.

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

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

Enum 과 관련하여 매우 흥미로운 Enums.NET 을 기록하고 싶을 수도 있습니다 .


1

이것이 나의 구현이다. 기본적으로 모든 속성을 설정할 수 있으며 작동합니다.

public static class EnumExtensions
    {
        public static string GetDescription(this Enum @enum)
        {
            Type type = @enum.GetType();
            FieldInfo fi = type.GetField(@enum.ToString());
            DescriptionAttribute[] attrs =
                fi.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];
            if (attrs.Length > 0)
            {
                return attrs[0].Description;
            }
            return null;
        }
    }

0

나중에 직접 캐스팅을 사용하는 것이 좋다면 System.Enum필요한 경우 메소드에서 기본 클래스를 사용할 수 있다고 생각합니다 . 유형 매개 변수를주의해서 교체하면됩니다. 따라서 메소드 구현은 다음과 같습니다.

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

그런 다음 다음과 같이 사용할 수 있습니다.

var parsedOutput = (YourEnum)EnumUtils.GetEnumFromString(someString, YourEnum.DefaultValue);

의 사용 Enum.ToObject()보다 유연한 결과를 얻을 것입니다. 추가되는, 당신은 전화를 할 필요가 부정하는 것 대소 문자 구분없이 문자열 비교 할 수ToLower()
— DiskJunky

-6

완전성을 위해 다음은 Java 솔루션입니다. C #에서도 동일한 작업을 수행 할 수 있다고 확신합니다. 코드의 어느 곳에서나 유형을 지정하지 않아도됩니다. 대신 구문 분석하려는 문자열에 유형을 지정하십시오.

문제는 문자열이 어떤 열거 형과 일치하는지 알 수있는 방법이 없다는 것입니다. 따라서 그 문제를 해결하는 것입니다.

문자열 값만 수락하는 대신 열거 형과 "enumeration.value"형식의 값을 모두 갖는 문자열을 수락하십시오. 작업 코드는 다음과 같습니다. Java 1.8 이상이 필요합니다. 이렇게하면 color = "red"대신 color = "Color.red"와 같은 XML을보다 정확하게 볼 수 있습니다.

열거 형 이름 도트 값 이름이 포함 된 문자열을 사용하여 acceptEnumeratedValue () 메서드를 호출합니다.

이 메소드는 공식 열거 값을 리턴합니다.

import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;


public class EnumFromString {

    enum NumberEnum {One, Two, Three};
    enum LetterEnum {A, B, C};


    Map<String, Function<String, ? extends Enum>> enumsByName = new HashMap<>();

    public static void main(String[] args) {
        EnumFromString efs = new EnumFromString();

        System.out.print("\nFirst string is NumberEnum.Two - enum is " + efs.acceptEnumeratedValue("NumberEnum.Two").name());
        System.out.print("\nSecond string is LetterEnum.B - enum is " + efs.acceptEnumeratedValue("LetterEnum.B").name());

    }

    public EnumFromString() {
        enumsByName.put("NumberEnum", s -> {return NumberEnum.valueOf(s);});
        enumsByName.put("LetterEnum", s -> {return LetterEnum.valueOf(s);});
    }

    public Enum acceptEnumeratedValue(String enumDotValue) {

        int pos = enumDotValue.indexOf(".");

        String enumName = enumDotValue.substring(0, pos);
        String value = enumDotValue.substring(pos + 1);

        Enum enumeratedValue = enumsByName.get(enumName).apply(value);

        return enumeratedValue;
    }


}
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.