如何获取整数值的枚举值? [英] How can I get the value of an enum for its integer value?

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

问题描述

在.NET的最新版本中,我可以通过这种方式检索枚举值:



 公开 枚举包装工
{
Aaron_Rodgers = 12
Eddie_Lacy = 26
Jordy_Nelson = 87
Candle_Robb = 18
Clay_Matthews = 52
Julius_Peppers = 56
};

private void button4253147968_Click( object sender,EventArgs e)
{
int packerNum = Convert.ToInt32(textBoxPackerNum.Text);
字符串 packerName = Enum.GetName( typeof (Packers),packerNum);
MessageBox.Show( String .Format( 编号为{0}的打包程序为{1},packerNum,packerName));
}





在textBoxPackerNum中输入52告诉我52号包装工人是Clay_Matthews等。



但是,GetName()不适用于.NET 3.5中的Enum



在旧版本中可以做什么.NET要检索这个值吗?

解决方案

首先,这不是Enum的用途。使用枚举执行此类任务实际上并不是一个好主意。让我们假设你给我们一个不好的例子...



这也适用于3.5(和3.5 CF):

< pre lang =cs> int x = 52 ;
Console.WriteLine(((Packers)x).ToString());





如果你想要类似的东西喜欢CF中的GetNames,从这里开始: http://www.nickharris.net/index.php/2010/01/07/enum-getnames-in-net-compact-framework-3-5/ [ ^ ]和这里: http://stackoverflow.com/questions/8835264 / how-to-enum-getvalues-in-net-3-5 [ ^ ]


In recent versions of .NET, I can retrieve the enum value this way:

public enum Packers
{
    Aaron_Rodgers = 12,
    Eddie_Lacy = 26,
    Jordy_Nelson = 87,
    Candle_Robb = 18,
    Clay_Matthews = 52,
    Julius_Peppers = 56
};

private void button4253147968_Click(object sender, EventArgs e)
{
    int packerNum = Convert.ToInt32(textBoxPackerNum.Text);
    String packerName = Enum.GetName(typeof(Packers), packerNum);
    MessageBox.Show(String.Format("Packer with number {0} is {1}", packerNum, packerName));
}



Entering "52" in textBoxPackerNum shows me "Packer with number 52 is Clay_Matthews" etc.

However, GetName() is not available for Enum in .NET 3.5

What can be done in older versions of .NET to retrieve this value?

解决方案

First of all, this is not what's Enum for. Using enum for such a task is really not a good idea. Let's suppose you have pnly given us a bad example...

This is working in 3.5 (and 3.5 CF) also:

int x = 52;
Console.WriteLine(((Packers)x).ToString());



If you want to have something similar like GetNames in CF, start here: http://www.nickharris.net/index.php/2010/01/07/enum-getnames-in-net-compact-framework-3-5/[^] and here: http://stackoverflow.com/questions/8835264/how-to-enum-getvalues-in-net-3-5[^]


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

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