45

我有一堂这样的课:

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"

我有这个代码来获取一个属性值:

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

如何获取所有属性及其值?

4

1 回答 1

91

我如何获得所有属性及其值?

首先,您需要区分字段属性。看起来你在这里有字段。所以你想要这样的东西:

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 参数才能使其正常工作,因为字段是静态的并且不属于该类的实例。

于 2012-09-18T10:16:32.110 回答