IT TIP

Enum.Parse (), 확실히 깔끔한 방법?

itqueen 2020. 12. 7. 21:21
반응형

Enum.Parse (), 확실히 깔끔한 방법?


열거 형이 있다고 가정하십시오.

public enum Colours
{
    Red,
    Blue
}

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

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

이는 발생합니다 System.ArgumentException을 "녹색"의 구성원이 아니기 때문에 Colours열거.

이제 저는 try / catch에서 코드를 래핑하는 것을 정말 싫어합니다. 각 Colours열거 형을 반복 하고 문자열 비교 를 수행하지 않는 깔끔한 방법은 colour없습니까?


Enum.IsDefined()먼저 사용 하여 try / catch에서 래핑하지 않도록합니다. 입력이 해당 열거 형의 유효한 멤버인지 여부에 대한 부울 값을 반환합니다.


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

단지에 스카이의 링크를 확장 닷넷 4 Enum.TryParse <> , 즉

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

아니요, "no-throw"방법은 없습니다 (다른 클래스에있는 TryParse).

그러나 하나의 도우미 메서드에서 try-catch 논리 (또는 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.Parse ()를 사용합니다.
" 신뢰 "란 오류없이 항상 유효한 열거 형이라는 것을 알고 있습니다.

But there are times when "you never know what you're gonna get", and for those times, you need to use a nullable return value. Since .net doesn't offer this baked in, you can roll your own. Here's my recipe:

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

To use this method, call it like so:

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

Just add this method to a class you use to store your other commonly used utility functions.

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

반응형