如何通过字符串或int获取枚举值 [英] How to get enum value by string or int

查看:265
本文介绍了如何通过字符串或int获取枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

在一些字符串变量中,我有如下值value1:

  string str =Value1

或在一些int变量中我有值2像

  int a = 2; 

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

解决方案

否,你不想要一个通用的方法。这很容易:

  MyEnum枚举=(MyEnum)myInt; 

MyEnum枚举=(MyEnum)Enum.Parse(typeof(TestEnum),myString);

我认为这也会更快。


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,
    Value2 = 2,
    Value3 = 3
}

and in some string variable I have the value "value1" as follows:

string str = "Value1" 

or in some int variable I have the value 2 like

int a = 2;

how can I get the instance of enum ? I want a generic method where I can provide the enum and my input string or int value to get the enum instance.

解决方案

No, you don't want a generic method. This is much easier:

MyEnum enum = (MyEnum)myInt;

MyEnum enum = (MyEnum)Enum.Parse(typeof(TestEnum), myString);

I think it will also be faster.

这篇关于如何通过字符串或int获取枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆