使用字符串从Enum类获取值 [英] Getting Value from a Enum class using string

查看:394
本文介绍了使用字符串从Enum类获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,


我在c#winforms应用程序中的枚举有问题.

我有一个foll0ws的枚举,

Hello all,


I have problem with enumeration in c# winforms application.

I have a Enum as foll0ws,

public enum Currency
{
   INR = 0,
   USD = 4545,
   JPY = 2152,
   EUR = 5241

}




我已将枚举项目填充到组合框中.


我想使用




I have populated the enum items in a combo box.


I want use the

combobox1.Text 

值来获取相应的数值.

例如:

当我从组合框中选择美元时,我必须使用枚举货币"来获取4545的值.




我该如何实现...

请帮帮我.

在此先感谢.

value to get the corresponding numeric value.

For Example :

When I select USD from the combobox, I have to Get the value of 4545 using the enum "Currency".




How can I achieve this...

Please help me.

Thanks in advance.

推荐答案

使用Enum.Parse.

Enum.Parse(类型,字符串)
将一个或多个枚举常量的名称或数值的字符串表示形式转换为等效的枚举对象.

Enum.Parse(类型,字符串,布尔值)
将一个或多个枚举常量的名称或数值的字符串表示形式转换为等效的枚举对象.参数指定操作是否区分大小写.
Use the Enum.Parse.

Enum.Parse (Type, String)
Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.

Enum.Parse (Type, String, Boolean)
Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. A parameter specifies whether the operation is case-sensitive.


Try:
enum testEnum
    {
    GBP = 100,
    USD = 200,
    }

...
testEnum te = (testEnum) Enum.Parse(typeof (testEnum), "USD");
...



[edit]
哦,在.NET 4.0及更高版本中,有一个(更可取的)TryParse:



[edit]
Oh, and in .NET 4.0 and above there is a (much preferable) TryParse:

Enum.TryParse<enumName>(stringNameOfEnumValue, out placeToPutValue);

[/edit]


这对我来说很好(我在设计模式下在表单上添加了一个名为 cbCurrencies ComboBox):
This works fine for me (I''ve added a ComboBox called cbCurrencies on the form in design mode):
public partial class Form1 : Form
{
    public enum Currency
    {
        INR = 0,
        USD = 4545,
        JPY = 2152,
        EUR = 5241
    }
    public Form1()
    {
        InitializeComponent();
        // Populate
        cbCurrencies.DataSource = System.Enum.GetValues(typeof(Currency));
    }
    private void cbCurrencies_SelectedIndexChanged(object sender, EventArgs e)
    {
        // Get the selected currency
        Currency cur = (Currency)cbCurrencies.SelectedValue;

        // And get the value in need
        int value = (int)cur;

    }
}



:)



:)


这篇关于使用字符串从Enum类获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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