How to get enum value by string or int

后端 未结 10 1273
慢半拍i
慢半拍i 2020-12-07 12:43

How can I get the enum value if I have the enum string or enum int value. eg: If i have an enum as follows:

public enum TestEnum
{
    Value1 = 1,
    Value         


        
10条回答
  •  被撕碎了的回忆
    2020-12-07 13:33

    Following is the method in C# to get the enum value by string

    ///
    /// Method to get enumeration value from string value.
    ///
    ///
    ///
    
    public T GetEnumValue(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;
    }
    

    Following is the method in C# to get the enum value by int.

    ///
    /// Method to get enumeration value from int value.
    ///
    ///
    ///
    
    public T GetEnumValue(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;
    }
    

    If I have an enum as follows:

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

    then I can make use of above methods as

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

    Hope this will help.

提交回复
热议问题