C# 遍历枚举?(索引 System.Array)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/482729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 05:09:35  来源:igfitidea点击:

C# Iterating through an enum? (Indexing a System.Array)

c#enumsiterationsystem.array

提问by TK.

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!

或者我完全错过了什么!

采纳答案by Frederik Gheysels

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:

或者,您可以转换返回的 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]);
}

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

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

回答by TWith2Sugars

What about using a foreach loop, maybe you could work with that?

使用 foreach 循环怎么样,也许你可以使用它?

  int i = 0;
  foreach (var o in values)
  {
    print(names[i], o);
    i++;
  }

something like that perhaps?

也许是这样的?

回答by Marc Gravell

You need to cast the array - the returned array is actually of the requested type, i.e. myEnum[]if you ask for typeof(myEnum):

您需要转换数组 - 返回的数组实际上是请求的类型,即myEnum[]如果您要求typeof(myEnum)

myEnum[] values = (myEnum[]) Enum.GetValues(typeof(myEnum));

Then values[0]etc

然后values[0]

回答by Arcturus

You can cast that Array to different types of Arrays:

您可以将该数组转换为不同类型的数组:

myEnum[] values = (myEnum[])Enum.GetValues(typeof(myEnum));

or if you want the integer values:

或者如果你想要整数值:

int[] values = (int[])Enum.GetValues(typeof(myEnum));

You can iterate those casted arrays of course :)

你当然可以迭代那些铸造的数组:)

回答by mrtaikandi

How about a dictionary list?

字典列表怎么样?

Dictionary<string, int> list = new Dictionary<string, int>();
foreach( var item in Enum.GetNames(typeof(MyEnum)) )
{
    list.Add(item, (int)Enum.Parse(typeof(MyEnum), item));
}

and of course you can change the dictionary value type to whatever your enum values are.

当然,您可以将字典值类型更改为您的枚举值。

回答by Bubblewrap

Array has a GetValue(Int32) method which you can use to retrieve the value at a specified index.

Array 有一个 GetValue(Int32) 方法,您可以使用它来检索指定索引处的值。

Array.GetValue

数组.GetValue

回答by Chev

Here is a simple way to iterate through your custom Enum object

这是迭代自定义 Enum 对象的简单方法

For Each enumValue As Integer In [Enum].GetValues(GetType(MyEnum))

     Print([Enum].GetName(GetType(MyEnum), enumValue).ToString)

Next

回答by Kevin Castle

Here is another. We had a need to provide friendly names for our EnumValues. We used the System.ComponentModel.DescriptionAttribute to show a custom string value for each enum value.

这是另一个。我们需要为我们的 EnumValues 提供友好的名称。我们使用 System.ComponentModel.DescriptionAttribute 来显示每个枚举值的自定义字符串值。

public static class StaticClass
{
    public static string GetEnumDescription(Enum currentEnum)
    {
        string description = String.Empty;
        DescriptionAttribute da;

        FieldInfo fi = currentEnum.GetType().
                    GetField(currentEnum.ToString());
        da = (DescriptionAttribute)Attribute.GetCustomAttribute(fi,
                    typeof(DescriptionAttribute));
        if (da != null)
            description = da.Description;
        else
            description = currentEnum.ToString();

        return description;
    }

    public static List<string> GetEnumFormattedNames<TEnum>()
    {
        var enumType = typeof(TEnum);
        if (enumType == typeof(Enum))
            throw new ArgumentException("typeof(TEnum) == System.Enum", "TEnum");

        if (!(enumType.IsEnum))
            throw new ArgumentException(String.Format("typeof({0}).IsEnum == false", enumType), "TEnum");

        List<string> formattedNames = new List<string>();
        var list = Enum.GetValues(enumType).OfType<TEnum>().ToList<TEnum>();

        foreach (TEnum item in list)
        {
            formattedNames.Add(GetEnumDescription(item as Enum));
        }

        return formattedNames;
    }
}

In Use

正在使用

 public enum TestEnum
 { 
        [Description("Something 1")]
        Dr = 0,
        [Description("Something 2")]
        Mr = 1
 }



    static void Main(string[] args)
    {

        var vals = StaticClass.GetEnumFormattedNames<TestEnum>();
    }

This will end returning "Something 1", "Something 2"

这将结束返回“Something 1”、“Something 2”

回答by Paul

Another solution, with interesting possibilities:

另一个解决方案,具有有趣的可能性:

enum Days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }

static class Helpers
{
public static IEnumerable<Days> AllDays(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;
  } 
}

回答by Frank Szczerba

You can simplify this using format strings. I use the following snippet in usage messages:

您可以使用格式字符串简化此操作。我在使用消息中使用以下代码段:

writer.WriteLine("Exit codes are a combination of the following:");
foreach (ExitCodes value in Enum.GetValues(typeof(ExitCodes)))
{
    writer.WriteLine("   {0,4:D}: {0:G}", value);
}

The D format specifier formats the enum value as a decimal. There's also an X specifier that gives hexadecimal output.

D 格式说明符将枚举值格式化为十进制。还有一个 X 说明符提供十六进制输出。

The G specifier formats an enum as a string. If the Flags attribute is applied to the enum then combined values are supported as well. There's an F specifier that acts as if Flags is always present.

G 说明符将枚举格式化为字符串。如果 Flags 属性应用于枚举,则也支持组合值。有一个 F 说明符,就像 Flags 总是存在一样。

See Enum.Format().

请参见 Enum.Format()。