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

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

问题描述

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

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
}

并且在某些字符串变量中,我的值为value1",如下所示:

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

string str = "Value1" 

或在某些 int 变量中,我的值 2 就像

or in some int variable I have the value 2 like

int a = 2;

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

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 myEnum = (MyEnum)myInt;

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

我认为它也会更快.

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

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