prosource

Enum.Parse(), 확실히 더 나은 방법이 있습니까?

probook 2023. 7. 7. 19:07
반응형

Enum.Parse(), 확실히 더 나은 방법이 있습니까?

내게 열거가 있다고 하면,

public enum Colours
{
    Red,
    Blue
}

구문 분석하는 유일한 방법은 다음과 같은 것을 수행하는 것입니다.

string colour = "Green";
var col = (Colours)Enum.Parse(typeOf(Colours),colour);

그러면 시스템이 느려집니다.논쟁"녹색"이 구성원이 아니기 때문에 예외입니다.Colours열거의

이제 저는 try/catch's에서 코드를 래핑하는 것을 정말 싫어합니다. 각 코드를 반복하지 않고 이 작업을 수행할 수 있는 더 좋은 방법은 없습니다.Colours열거, 그리고 문자열 비교하기colour?

먼저 사용하여 시도/캐치에 포장되지 않도록 합니다.입력이 해당 열거형의 유효한 멤버인지 여부에 대한 부울 값을 반환합니다.

4.0에는 Enum이 있다고 생각합니다.트라이파스

그렇지 않으면 확장 방법을 사용합니다.

public static bool TryParse<T>(this Enum theEnum, string valueToParse, out T returnValue)
{
    returnValue = default(T);
    int intEnumValue;
    if (Int32.TryParse(valueToParse, out intEnumValue))
    {
        if (Enum.IsDefined(typeof(T), intEnumValue))
        {
            returnValue = (T)(object)intEnumValue;
            return true;
        }
    }
    return false;
}

Sky의 링크를 확장하기 위해서입니다.넷 4 열거형.Parse를 사용해 보세요.

Enum.TryParse<TEnum>(
    string value,
    [bool ignoreCase,]
    out TEnum result
)

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

    enum Colour
    {
        Red,
        Blue
    }

    private void ParseColours()
    {
        Colour aColour;

        // IMO using the actual enum type is intuitive, but Resharper gives 
        // "Access to a static member of a type via a derived type"
        if (Colour.TryParse("RED", true, out aColour))
        {
           // ... success
        }

        // OR, the compiler can infer the type from the out
        if (Enum.TryParse("Red", out aColour))
        {
           // ... success
        }

        // OR explicit type specification
        // (Resharper: Type argument specification is redundant)
        if (Enum.TryParse<Colour>("Red", out aColour))
        {
          // ... success
        }
    }

아니요, 이것에 대한 "투구 금지" 방법은 없습니다(다른 클래스에 있는 laTryParse).

그러나 앱 코드를 오염시키지 않도록 하나의 도우미 방법으로 시도 캐치 로직(또는 IsDefined 체크)을 캡슐화할 수 있도록 사용자가 직접 작성할 수 있습니다.

public static object TryParse(Type enumType, string value, out bool success)
{
  success = Enum.IsDefined(enumType, value);
  if (success)
  {
    return Enum.Parse(enumType, value);
  }
  return null;
}

신뢰할 수 있는 열거형을 구문 분석하는 경우 Enum을 사용합니다.구문 분석().
"신뢰할 수 있는"이란 말은, 항상 오류 없이 유효한 열거형이 될 것이라는 것을 알고 있습니다.절대로!

하지만 "당신이 무엇을 얻을지 절대 알 수 없는" 경우가 있으며, 그러한 경우에는 무효 반환 값을 사용해야 합니다..net은 이 베이크 인을 제공하지 않기 때문에, 당신은 당신 자신의 베이크 인을 할 수 있습니다.제 레시피는 다음과 같습니다.

public static TEnum? ParseEnum<TEnum>(string sEnumValue) where TEnum : struct
{
    TEnum eTemp;
    TEnum? eReturn = null;
    if (Enum.TryParse<TEnum>(sEnumValue, out eTemp) == true)
        eReturn = eTemp;
    return eReturn;
}

이 방법을 사용하려면 다음과 같이 부릅니다.

eColor? SelectedColor = ParseEnum<eColor>("Red");

일반적으로 사용되는 다른 유틸리티 함수를 저장하는 데 사용하는 클래스에 이 메서드를 추가하기만 하면 됩니다.

언급URL : https://stackoverflow.com/questions/2394725/enum-parse-surely-a-neater-way

반응형