C# 如何通过字符串或int获取枚举值

C# 如何通过字符串或int获取枚举值,c#,enums,C#,Enums,如果我有枚举字符串或枚举int值,如何获取枚举值。例如:如果我有如下枚举: public enum TestEnum { Value1 = 1, Value2 = 2, Value3 = 3 } string str = "Value1" 在某个字符串变量中,值“value1”如下所示: public enum TestEnum { Value1 = 1, Value2 = 2, Value3 = 3 } string str = "Val

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

public enum TestEnum
{
    Value1 = 1,
    Value2 = 2,
    Value3 = 3
}
string str = "Value1" 
在某个字符串变量中,值“value1”如下所示:

public enum TestEnum
{
    Value1 = 1,
    Value2 = 2,
    Value3 = 3
}
string str = "Value1" 
或者在一些int变量中,我的值是2,比如

int a = 2;

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

下面是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;
}
然后我可以使用上述方法作为参考

TestEnum reqValue = GetEnumValue<TestEnum>("Value1");  // Output: Value1
TestEnum reqValue2 = GetEnumValue<TestEnum>(2);        // OutPut: Value2
TestEnum reqValue=GetEnumValue(“值1”);//输出:值1
TestEnum reqValue2=GetEnumValue(2);//输出:值2

希望这会有所帮助。

我想您忘记了泛型类型定义:

public T GetEnumValue<T>(int intValue) where T : struct, IConvertible // <T> added
public T GetEnumValue(int intValue),其中添加了T:struct,IConvertible//
您可以将其改进为最方便的方式,例如:

public static T ToEnum<T>(this string enumValue) : where T : struct, IConvertible
{
    return (T)Enum.Parse(typeof(T), enumValue);
}
publicstatict-ToEnum(此字符串枚举值):其中T:struct,IConvertible
{
返回(T)Enum.Parse(typeof(T),enumValue);
}
然后你可以做:

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

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

MyEnum myEnum = (MyEnum)myInt;

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

我想它也会更快。

试试这样的

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

TestEnum en = "Value1".GetMyEnum();

如果使用
TryParse
Parse
ToObject
方法,可能会简单得多

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);
    }
}
公共静态类EnumHelper
{
公共静态T GetEnumValue(字符串str),其中T:struct,IConvertible
{
类型enumType=typeof(T);
如果(!enumType.IsEnum)
{
抛出新异常(“T必须是枚举类型”);
}
T值;
返回Enum.TryParse(str,true,out val)?val:默认值(T);
}
公共静态T GetEnumValue(int intValue),其中T:struct,IConvertible
{
类型enumType=typeof(T);
如果(!enumType.IsEnum)
{
抛出新异常(“T必须是枚举类型”);
}
返回(T)Enum.ToObject(enumType,intValue);
}
}
正如@chrfin在注释中所指出的,只需在方便的参数类型之前添加
this
,就可以很容易地将其作为扩展方法。

只需尝试一下

这是另一种方式

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

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

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

    /// <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>();
    }
//
///扩展方法返回给定字符串的T类型枚举值。
/// 
/// 
/// 
/// 
公共静态T ToEnum(此字符串值)
{
返回(T)Enum.Parse(typeof(T),value,true);
}
/// 
///用于为给定int返回类型为T的枚举值的扩展方法。
/// 
/// 
/// 
/// 
公共静态T ToEnum(此int值)
{
var name=Enum.GetName(typeof(T),value);
返回name.ToEnum();
}

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

SqlDataReader dr = selectCmd.ExecuteReader();
while (dr.Read()) {
   EnumType et = (EnumType)Enum.Parse(typeof(EnumType), dr.GetString(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"));
        }
    }


您可以使用以下方法进行此操作:

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...");
    }
公共静态输出GetEnumItem(输入)
{
//输出类型检查。。。
if(typeof(Output).BaseType!=typeof(Enum))
抛出新异常(“异常消息…”);
//输入类型检查:字符串类型
如果(输入的类型)=字符串的类型)
返回(输出)枚举解析(typeof(输出),(动态)输入);
//输入类型检查:整数类型
if(typeof(Input)=typeof(Int16)||
typeof(输入)=typeof(Int32)||
typeof(输入)=typeof(Int64))
返回(输出)(动态)输入;
抛出新异常(“异常消息…”);
}

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

您还可以提供从何处获得此方法的参考信息吗?为了编译此方法,我必须将第一行修改为public T GetEnumValue(int intValue),其中T:struct,IConvertible也要注意结尾处的额外“}”现在的可能重复也要在参数中添加一个
this
,并使
EnumHelper
静态,您也可以将它们用作扩展(请参见我的答案,但您有一个更好的/完整的代码用于其余部分)…@chrfin好主意,但我不喜欢它,因为它将在intellisense中突然出现,当我们在作用域中有名称空间时,它是不需要的。我想这会很烦人。@chrfin谢谢你的评论,并在我的回答中加上注释。这实际上是正确的做法。没有通用的方法来解析类型,这与没有IParsable接口的原因是一样的。@Johannes这是什么意思?有一种通用的方法,请参考我的答案和其他答案。@SriramSakthivel OP描述的问题已经解决了,就像KendallFrey展示的那样。无法完成泛型分析-请参阅此处:。与C#的“板载”解决方案相比,任何其他解决方案都没有优势。您可以拥有的最大值是ICanSetFromString,您可以在其中创建一个对象并将其初始化为其默认值(T),然后在下一步中传递一个代表性字符串。这与OP给出的答案很接近,但毫无意义,因为这通常是一个设计问题,而系统设计中遗漏了更大的一点。这个答案非常有效,特别是在使用int和string的多个示例中。谢谢。我认为现在可以了,它更简洁了一点:Enum.Parse(myString);
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...");
    }