「Unity/Csharp/クラス/クラスメンバfor取得」の版間の差分
提供: 初心者エンジニアの簡易メモ
(ページの作成:「== <pre> using System; using System.Reflection; public class ErrorCode { public const int USER_NOT_AGE = 1001; public const int USER_NOT_NAME = 1002; } class Pr...」) |
|||
行1: | 行1: | ||
− | == | + | ==クラスのメンバの値をforeachで取得== |
<pre> | <pre> | ||
using System; | using System; |
2025年3月13日 (木) 18:48時点における最新版
クラスのメンバの値をforeachで取得
using System; using System.Reflection; public class ErrorCode { public const int USER_NOT_AGE = 1001; public const int USER_NOT_NAME = 1002; } class Program { static void Main() { Type type = typeof(ErrorCode); FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy); foreach (FieldInfo field in fields) { string name = field.Name; // フィールド名(定数名) int value = (int)field.GetValue(null); // 定数の値 Debug.Log($"{name} = {value}"); } } }