如何通过字符串或整数获取枚举值


108

如果我有枚举字符串或枚举int值,如何获取枚举值。例如:如果我有如下枚举:

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

在某些字符串变量中,我的值是“ value1”,如下所示:

string str = "Value1" 

或在一些int变量中,我的值是2

int a = 2;

我如何获得enum的实例?我想要一个通用方法,可以在其中提供枚举和输入字符串或int值来获取枚举实例。


Answers:


209

不,您不需要通用方法。这要容易得多:

MyEnum myEnum = (MyEnum)myInt;

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

我认为它也会更快。


这实际上是正确的方法。出于没有IParsable接口的相同原因,没有通用的方法来解析类型。
约翰内斯

@Johannes这是什么意思?有一种通用的方法,也可以参考我的回答。
Sriram Sakthivel 2014年

1
@SriramSakthivel OP所描述的问题已解决,就像KendallFrey展示的那样。常规解析无法完成-参见此处:notifyit.com/blogs/blog.aspx?uk=Why-no-IParseable-interface。与C#的“内置”解决方案相比,任何其他解决方案都没有优势。您可以拥有的最大值是ICanSetFromString <T>,您可以在其中创建对象并将其初始化为其default(T),然后在下一步中传递代表字符串。这与OP给出的答案很接近-但却没有意义,因为通常这是一个设计问题,而系统设计中的一个更大的问题被遗漏了。
约翰内斯

这个答案非常有效,特别是在使用int和string的多个示例中。谢谢。
Termato 2015年

1
我认为这现在可以正常工作,它更加简洁:Enum.Parse <MyEnum>(myString);
Phil B

32

有很多方法可以做到这一点,但是如果您想举一个简单的例子,那就可以了。它只需要通过必要的防御性编码进行增强,以检查类型安全性和无效的解析等。

    /// <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>();
    }

16

如果使用TryParseorParseToObject方法,可能会简单得多。

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的参数类型之前添加,即可非常轻松地使其成为扩展方法。


1
现在,还this向参数添加a并使其为EnumHelperstatic,您也可以将其用作扩展名(请参阅我的答案,但其余部分则具有更好的/完整的代码)...
Christoph Fink 2014年

@chrfin是个好主意,但是我不喜欢它,因为它将在intellisense中弹出,而当我们在作用域中有名称空间时就不需要它了。我猜这会很烦。
Sriram Sakthivel 2014年

1
@chrfin感谢您的评论,并在我的回答中添加为注释。
Sriram Sakthivel 2014年

5

以下是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;
}

以下是C#中通过int获取枚举值的方法。

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

希望这会有所帮助。


4
您还可以提供哪里的参考吗?
2014年

为了对此进行编译,我不得不将第一行修改为public T GetEnumValue <T>(int intValue),其中T:struct,IConvertible最后还要注意一个额外的'}'
Avi

3

我认为您忘记了通用类型定义:

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>();

2

试试这个

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

所以你可以做

TestEnum en = "Value1".GetMyEnum();

2

从SQL数据库获取枚举,如:

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

2

只需尝试一下

这是另一种方式

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

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

0

这是获取字符串/值的示例

    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

0

您可以使用以下方法来做到这一点:

public static Output GetEnumItem<Output, Input>(Input input)
    {
        //Output type checking...
        if (typeof(Output).BaseType != typeof(Enum))
            throw new Exception("Exception message...");

        //Input type checking: string type
        if (typeof(Input) == typeof(string))
            return (Output)Enum.Parse(typeof(Output), (dynamic)input);

        //Input type checking: Integer type
        if (typeof(Input) == typeof(Int16) ||
            typeof(Input) == typeof(Int32) ||
            typeof(Input) == typeof(Int64))

            return (Output)(dynamic)input;

        throw new Exception("Exception message...");
    }

注意:此方法仅是示例,您可以对其进行改进。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.