C# Enum(列挙型)の値をループするサンプル

環境
Windows 11 Home 64bit
Microsoft Visual Studio Community 2022

構文
foreach(string value in Enum.GetNames(typeof(Names)))
{
//ループ処理コード
}
ループ処理内では、ループ変数でEnumの値を数値として取得できます。
上記のforeachループは、Enumの値を数値としてループします。
Enum.GetValues()の引数でtypeof()を呼び出し、typeof()の引数に列挙型を指定します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
using System;
using System.Collections.Generic;
public class Example
{
public enum Names
{
Jiro = 18,
Yokoku = 37,
Kazuma = 16,
Keiko = 24,
Megumi = 11,
}
public static void Main()
{
foreach(int value in Enum.GetValues(typeof(Names)))
{
Console.WriteLine(value);
}
}
}
using System; using System.Collections.Generic; public class Example { public enum Names { Jiro = 18, Yokoku = 37, Kazuma = 16, Keiko = 24, Megumi = 11, } public static void Main() { foreach(int value in Enum.GetValues(typeof(Names))) { Console.WriteLine(value); } } }
using System;
using System.Collections.Generic;
public class Example
{
    public enum Names 
    {
        Jiro = 18,
        Yokoku = 37,
        Kazuma = 16,
        Keiko = 24,
        Megumi = 11,
    }
    
    public static void Main()
    {
        foreach(int value in Enum.GetValues(typeof(Names)))
        {
            Console.WriteLine(value);
        }
    }
}

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
11
16
18
24
37
11 16 18 24 37
11
16
18
24
37

 

IT

Posted by arkgame