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

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

问题描述

我有以下代码:

// 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));
}

或者,您可以转换返回的 System.Array:

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]);
}

但是,您能确定 GetValues 返回值的顺序与 GetNames 返回名称的顺序相同吗?

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天全站免登陆