C#通过遍历枚举? (索引一个的System.Array) [英] C# Iterating through an enum? (Indexing a System.Array)

查看:261
本文介绍了C#通过遍历枚举? (索引一个的System.Array)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code:

  //获取内myEnum所有元素的字符串名称
的String [] =名称Enum.GetNames(typeof运算(myEnum));//取得内myEnum所有元素的值
数组值= Enum.GetValues​​(typeof运算(myEnum));//打印的名称和值到文件
的for(int i = 0; I< names.Length;我++)
{
    打印(名称[I],数值[I]);
}

不过,我不能索引值。是否有更简单的方法来做到这一点?

还是我错过了一些东西完全!


解决方案

 数组值= Enum.GetValues​​(typeof运算(myEnum));的foreach(价值观MyEnum VAL)
{
   Console.WriteLine(的String.Format({0}:{1},Enum.GetName(typeof运算(MyEnum),VAL),VAL));
}

或者,您可以施放返回的System.Array的:

 的String [] =名称Enum.GetNames(typeof运算(MyEnum));
MyEnum [] =值(MyEnum [])Enum.GetValues​​(typeof运算(MyEnum));的for(int i = 0; I< names.Length;我++)
{
    打印(名称[I],数值[I]);
}

但是,你可以确信,在GetValues​​方法相同的顺序GetNames返回名称返回值?

I have the following code:

// Obtain the string names of all the elements within myEnum 
String[] names = Enum.GetNames( typeof( myEnum ) );

// Obtain the values of all the elements within myEnum 
Array values = Enum.GetValues( typeof( myEnum ) );

// Print the names and values to file
for ( int i = 0; i < names.Length; i++ )
{
    print( names[i], values[i] ); 
}

However, I cannot index values. Is there an easier way to do this?

Or have I missed something entirely!

解决方案

Array values = Enum.GetValues(typeof(myEnum));

foreach( MyEnum val in values )
{
   Console.WriteLine (String.Format("{0}: {1}", Enum.GetName(typeof(MyEnum), val), val));
}

Or, you can cast the System.Array that is returned:

string[] names = Enum.GetNames(typeof(MyEnum));
MyEnum[] values = (MyEnum[])Enum.GetValues(typeof(MyEnum));

for( int i = 0; i < names.Length; i++ )
{
    print(names[i], values[i]);
}

But, can you be sure that GetValues returns the values in the same order as GetNames returns the names ?

这篇关于C#通过遍历枚举? (索引一个的System.Array)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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