简体   繁体   English

如何使用反射获取类的所有静态属性及其值

[英]How to get all static properties and its values of a class using reflection

I hava a class like this: 我有一个这样的课:

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";
}

I want to write some statement that returns a Dictionary<string, string> that has these values: 我想写一些语句,返回一个包含以下值的Dictionary<string, string>

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

I have this code for getting one property value: 我有这个代码来获取一个属性值:

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;
}

How I can get all properties and their values? 我如何获得所有房产及其价值?

how I can get all properties and their values? 我如何获得所有属性及其价值?

Well to start with, you need to distinguish between fields and properties . 首先,您需要区分字段属性 It looks like you've got fields here. 看起来你在这里有田地。 So you'd want something like: 所以你想要的东西是这样的:

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));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM