リフレクションを使用してクラスのすべての静的プロパティとその値を取得する方法 質問する

リフレクションを使用してクラスのすべての静的プロパティとその値を取得する方法 質問する

次のようなクラスがあります:

public class tbl050701_1391_Fields
{
    public static readonly string StateName = "State Name";
    public static readonly string StateCode = "State Code";
    public static readonly string AreaName = "Area Name";
    public static readonly string AreaCode = "Area Code";
    public static readonly string Dore = "Period";
    public static readonly string Year = "Year";
}

次の値を持つ を返すステートメントを記述したいと思いますDictionary<string, string>

Key                            Value
--------------------------------------------
"StateName"                    "State Name"
"StateCode"                    "State Code"
"AreaName"                     "Area Name"
"Dore"                         "Period"
"Year"                         "Year"

1 つのプロパティ値を取得するためのコードは次のとおりです。

public static string GetValueUsingReflection(object obj, string propertyName)
{
    var field = obj.GetType().GetField(propertyName, BindingFlags.Public | BindingFlags.Static);
    var fieldValue = field != null ? (string)field.GetValue(null) : string.Empty;
    return fieldValue;
}

すべてのプロパティとその値を取得するにはどうすればよいですか?

ベストアンサー1

すべてのプロパティとその値を取得するにはどうすればよいですか?

まず、次のことを区別する必要があります田畑そしてプロパティここにフィールドがあるようです。つまり、次のようなものが必要になります。

public static Dictionary<string, string> GetFieldValues(object obj)
{
    return obj.GetType()
              .GetFields(BindingFlags.Public | BindingFlags.Static)
              .Where(f => f.FieldType == typeof(string))
              .ToDictionary(f => f.Name,
                            f => (string) f.GetValue(null));
}

注: フィールドは静的であり、クラスのインスタンスに属していないため、GetValue が機能するには null パラメータが必要です。

おすすめ記事