Program Tip

문자열 또는 정수로 열거 형 값을 얻는 방법

programtip 2020. 10. 31. 10:00
반응형

문자열 또는 정수로 열거 형 값을 얻는 방법


enum string 또는 enum int 값이 있으면 어떻게 enum 값을 얻을 수 있습니까? 예 : 다음과 같이 열거 형이있는 경우 :

public enum TestEnum
{
    Value1 = 1,
    Value2 = 2,
    Value3 = 3
}

일부 문자열 변수에는 다음과 같이 "value1"값이 있습니다.

string str = "Value1" 

또는 일부 int 변수에는 2와 같은 값이 있습니다.

int a = 2;

enum의 인스턴스를 어떻게 얻을 수 있습니까? enum 인스턴스를 얻기 위해 enum과 입력 문자열 또는 int 값을 제공 할 수있는 일반 메서드를 원합니다.


아니요, 일반적인 방법은 원하지 않습니다. 이것은 훨씬 쉽습니다.

MyEnum myEnum = (MyEnum)myInt;

MyEnum myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), myString);

나는 또한 더 빠를 것이라고 생각합니다.


이 작업을 수행하는 방법에는 여러 가지가 있지만 간단한 예제를 원한다면 그렇게 할 것입니다. 유형 안전성 및 유효하지 않은 구문 분석 등을 확인하기 위해 필요한 방어 코딩으로 향상되어야합니다.

    /// <summary>
    /// Extension method to return an enum value of type T for the given string.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="value"></param>
    /// <returns></returns>
    public static T ToEnum<T>(this string value)
    {
        return (T) Enum.Parse(typeof(T), value, true);
    }

    /// <summary>
    /// Extension method to return an enum value of type T for the given int.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="value"></param>
    /// <returns></returns>
    public static T ToEnum<T>(this int value)
    {
        var name = Enum.GetName(typeof(T), value);
        return name.ToEnum<T>();
    }

TryParse또는 ParseToObject메서드 를 사용하면 훨씬 간단 할 수 있습니다 .

public static class EnumHelper
{
    public static  T GetEnumValue<T>(string str) where T : struct, IConvertible
    {
        Type enumType = typeof(T);
        if (!enumType.IsEnum)
        {
            throw new Exception("T must be an Enumeration type.");
        }
        T val;
        return Enum.TryParse<T>(str, true, out val) ? val : default(T);
    }

    public static T GetEnumValue<T>(int intValue) where T : struct, IConvertible
    {
        Type enumType = typeof(T);
        if (!enumType.IsEnum)
        {
            throw new Exception("T must be an Enumeration type.");
        }

        return (T)Enum.ToObject(enumType, intValue);
    }
}

@chrfin 주석에서 언급했듯이 this, 매개 변수 유형 앞에 추가 하기 만하면 편리 할 수 있는 확장 메소드로 매우 쉽게 만들 수 있습니다.


다음은 문자열로 열거 형 값을 가져 오는 C #의 메서드입니다.

    ///
    /// Method to get enumeration value from string value.
    ///
    ///
    ///

    public T GetEnumValue<T>(string str) where T : struct, IConvertible
    {
        if (!typeof(T).IsEnum)
        {
            throw new Exception("T must be an Enumeration type.");
        }
        T val = ((T[])Enum.GetValues(typeof(T)))[0];
        if (!string.IsNullOrEmpty(str))
        {
            foreach (T enumValue in (T[])Enum.GetValues(typeof(T)))
            {
                if (enumValue.ToString().ToUpper().Equals(str.ToUpper()))
                {
                    val = enumValue;
                    break;
                }
            }
        }

        return val;
    }

다음은 int로 열거 형 값을 가져 오는 C #의 메서드입니다.

    ///
    /// Method to get enumeration value from int value.
    ///
    ///
    ///

    public T GetEnumValue<T>(int intValue) where T : struct, IConvertible
    {
        if (!typeof(T).IsEnum)
        {
            throw new Exception("T must be an Enumeration type.");
        }
        T val = ((T[])Enum.GetValues(typeof(T)))[0];

        foreach (T enumValue in (T[])Enum.GetValues(typeof(T)))
        {
            if (Convert.ToInt32(enumValue).Equals(intValue))
            {
                val = enumValue;
                break;
            }             
        }
        return val;
    }

다음과 같은 열거 형이있는 경우 :

public enum TestEnum
    {
        Value1 = 1,
        Value2 = 2,
        Value3 = 3
    }

그런 다음 위의 방법을 다음과 같이 사용할 수 있습니다.

TestEnum reqValue = GetEnumValue<TestEnum>("Value1");  // Output: Value1
TestEnum reqValue2 = GetEnumValue<TestEnum>(2);       // OutPut: Value2

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


제네릭 유형 정의를 잊은 것 같습니다.

public T GetEnumValue<T>(int intValue) where T : struct, IConvertible // <T> added

다음과 같이 가장 편리하게 개선 할 수 있습니다.

public static T ToEnum<T>(this string enumValue) : where T : struct, IConvertible
{
    return (T)Enum.Parse(typeof(T), enumValue);
}

그러면 다음을 수행 할 수 있습니다.

TestEnum reqValue = "Value1".ToEnum<TestEnum>();

SQL 데이터베이스에서 다음과 같이 열거 형을 가져옵니다.

SqlDataReader dr = selectCmd.ExecuteReader();
while (dr.Read()) {
   EnumType et = (EnumType)Enum.Parse(typeof(EnumType), dr.GetString(0));
   ....         
}

이런 식으로 시도

  public static TestEnum GetMyEnum(this string title)
        {    
            EnumBookType st;
            Enum.TryParse(title, out st);
            return st;          
         }

그래서 당신은 할 수 있습니다

TestEnum en = "Value1".GetMyEnum();

간단히 시도하십시오

다른 방법입니다

public enum CaseOriginCode
    {
        Web = 0,
        Email = 1,
        Telefoon = 2
    }

public void setCaseOriginCode(string CaseOriginCode)
{
    int caseOriginCode = (int)(CaseOriginCode)Enum.Parse(typeof(CaseOriginCode), CaseOriginCode);
}

당신의 기사에 대한 코멘트입니다


다음은 문자열 / 값을 얻는 예입니다.

    public enum Suit
    {
        Spades = 0x10,
        Hearts = 0x11,
        Clubs = 0x12,
        Diamonds = 0x13
    }

    private void print_suit()
    {
        foreach (var _suit in Enum.GetValues(typeof(Suit)))
        {
            int suitValue = (byte)(Suit)Enum.Parse(typeof(Suit), _suit.ToString());
            MessageBox.Show(_suit.ToString() + " value is 0x" + suitValue.ToString("X2"));
        }
    }

    Result of Message Boxes
    Spade value is 0x10
    Hearts value is 0x11
    Clubs value is 0x12
    Diamonds value is 0x13

참고 URL : https://stackoverflow.com/questions/23563960/how-to-get-enum-value-by-string-or-int

반응형