我有以下代码:
// 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] ); }
但是,我无法索引值.有更简单的方法吗?
或者我完全错过了什么!
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:
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返回名称相同的顺序返回值吗?
你需要强制转换数组 - 返回的数组实际上是所请求的类型,即myEnum[]
如果你要求typeof(myEnum)
:
myEnum[] values = (myEnum[]) Enum.GetValues(typeof(myEnum));
然后values[0]
等
您可以将该数组转换为不同类型的数组:
myEnum[] values = (myEnum[])Enum.GetValues(typeof(myEnum));
或者如果你想要整数值:
int[] values = (int[])Enum.GetValues(typeof(myEnum));
你可以迭代那些铸造的数组当然:)
字典列表怎么样?
Dictionarylist = new Dictionary (); foreach( var item in Enum.GetNames(typeof(MyEnum)) ) { list.Add(item, (int)Enum.Parse(typeof(MyEnum), item)); }
当然,您可以将字典值类型更改为您的枚举值.
另一个解决方案,有趣的可能:
enum Days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } static class Helpers { public static IEnumerableAllDays(Days First) { if (First == Days.Monday) { yield return Days.Monday; yield return Days.Tuesday; yield return Days.Wednesday; yield return Days.Thursday; yield return Days.Friday; yield return Days.Saturday; yield return Days.Sunday; } if (First == Days.Saturday) { yield return Days.Saturday; yield return Days.Sunday; yield return Days.Monday; yield return Days.Tuesday; yield return Days.Wednesday; yield return Days.Thursday; yield return Days.Friday; } }