【问题标题】:How to get all static properties and its values of a class using reflection如何使用反射获取类的所有静态属性及其值
【发布时间】:2012-09-18 10:13:50
【问题描述】:

我有一个这样的课程:

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

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

【问题讨论】:

  • 那些是静态字段,而不是静态属性。你两个都想要吗?还是只有字段?

标签: c# reflection


【解决方案1】:

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

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

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

【讨论】:

  • 我必须使用 BindingFlags.NonPublic 和 public object MyObject { get; private set; }
  • @jonyfries:是的,因为那里没有任何公共字段——你有一个公共属性。根据我回答的第一部分,问题中的代码具有公共字段。如果您想使用属性,请致电GetProperties。如果你想访问支持自动实现属性的字段,你需要指定BindingFlags.NonPublic,因为它们是私有的。
猜你喜欢
  • 2010-10-01
  • 2011-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多