从枚举中获取所有整数值 [英] Get all integer values from an enumeration

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

问题描述

考虑我有这样的调查员:



  enum  ProgramDeclaration 
{
program = 1
identifier = 2
leftcurly = 3
};





并且通过foreach获取所有值我使用此代码:

  foreach (ProgramDeclaration val  in  Enum.GetValues( typeof (ProgramDeclaration)))
{
MessageBox.Show(val.ToString());
}



问题:以上代码只给我输出:

program

标识符

leftcurly



问题:如何获得整数值1,2和3?我想在消息框中显示它吗?



我尝试过:



在MSDN上寻找任何样本,但我什么都没有..

解决方案

尝试:

 < span class =code-keyword> foreach (ProgramDeclaration val  in  Enum.GetValues( typeof (ProgramDeclaration)))
{
Console.WriteLine( 值:{0}和整数值:{1},val,( int )val);
}


当然,如果<$ c,你将不会得到 int $ c> val 被声明为枚举,枚举中有一个该项的值。



如果你想要整数值,然后得到整数值!这很简单!

  foreach  int  val   Enum.GetValues( typeof (ProgramDeclaration)))
{
MessageBox.Show(val.ToString());
}





顺便提一下,文档中的样本记录很清楚:

Enum.GetValues方法(类型)(系统) [ ^ ]



甚至花费更少的时间在Visual Studio中进行F1以获得编写类似这样的问题的在线帮助。


请参阅我的文章,全面分析基于反射的枚举类型: 枚举类型不枚举!解决.NET和语言限制



基于 GetValues的简单方法确实有效,但是当您使用相同的基础整数值定义不同的枚举成员时,您会遇到问题。这种情况在实践中非常重要。除其他事项外,我的文章详细解释了这种情况,并提供了一种独立于指定值的方法。



-SA

Consider i have enumerator like this :

enum ProgramDeclaration
 {
     program=1,
     identifier=2,
     leftcurly=3
 };



and to get all values via foreach i use this code :

foreach (ProgramDeclaration val in Enum.GetValues(typeof(ProgramDeclaration)))
{
    MessageBox.Show(val.ToString());
}


Problem : above code only give me output :
program
identifier
leftcurly

Question : how to get the integer value 1, 2 and 3? i want to show it in messagebox?

What I have tried:

looking for any sample on MSDN but i got nothing..

解决方案

Try:

foreach (ProgramDeclaration val in Enum.GetValues(typeof(ProgramDeclaration)))
{
    Console.WriteLine("Value : {0} and Integer Value : {1}", val, (int) val);    
}


For sure, you won't get an int if val is declared as an enumeration and there is an item in the enumeration for that value.

If you want integer values, then get integer value! This is as simple as that!

foreach (int val in Enum.GetValues(typeof(ProgramDeclaration)))
{
    MessageBox.Show(val.ToString());
}



By the way, this is well documented with samples in the documentation:
Enum.GetValues Method (Type) (System)[^]

And it would even take less time to do F1 in Visual Studio to get online help that it take to write a question like this one.


Please see my article with comprehensive analysis of enumeration types based on reflection: Enumeration Types do not Enumerate! Working around .NET and Language Limitations.

The simpler method based on GetValues does work, but there are problems you face when you define different enumeration members with identical underlying integer values. Such cases are very important in practice. My article, among other things, explains this situation in detail and provides a method independent of the assigned values.

—SA


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

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