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 #에 컴파일러 적용 형식 안전 일반 솔루션을 게시 했습니다 . 솔루션에서 페이지가 더 위로 올라가면이 편집 내용을 제거하겠습니다.
답변
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. 기회는 드물다.
답변
이 기능은 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);답변
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 유형 및 모든 인터페이스 유형으로 제한합니다.
답변
편집하다
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;
    }
}답변
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 매개 변수는 입력 대소 문자를 무시하기위한 것입니다.
답변
또한 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 이상을 사용하면 구문이 완벽하게 나타납니다.
답변
나는 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);
    }
}