首页 > 解决方案 > 如何使用反射来获取对象中的所有变量?

问题描述

我目前正在使用此代码来获取对象中的所有变量并将数据放在字典中(键是变量名,值是变量的内容)。

foreach (var property in PropertiesOfType<string>(propertiesJSON))
{
    dictionary.Add(property.Key, property.Value);
}

在这段代码中,propertiesJSON是我需要的对象。这是 PropertiesOfType 方法:

public static IEnumerable<KeyValuePair<string, T>> PropertiesOfType<T>(object obj)
{
    return from p in obj.GetType().GetProperties()
           where p.PropertyType == typeof(T)
           select new KeyValuePair<string, T>(p.Name, (T)p.GetValue(obj));
}

当我为任何数据测试我的 Dictionary 时,没有任何值(我使用 Visual Studio 的调试工具进行检查,我的程序还打印了 Dictionary 内的所有数据 - 当然,不存在)。请告诉我我在这里犯的错误(我还在学习编码,我在发布这篇文章时才 15 岁)。

编辑:这就是 propertiesJSON 的样子

var propertiesJSON = Newtonsoft.Json.JsonConvert.DeserializeObject<Models.PropertiesJSON>(content);

这是课程本身:

class PropertiesJSON
{
    public string botToken;
    public bool girl;
    public int age;
    public string[] hi;
    public string test;
}

提前致谢。

标签: c#dictionaryreflection

解决方案


那些不是属性!

这些:

public string botToken;
public bool girl;
public int age;
public string[] hi;
public string test;

都是领域。如果它们是属性,它们将如下所示:

public string botToken { get; }
public bool girl  { get; }
public int age  { get; }
public string[] hi  { get; }
public string test  { get; }

要获取字段,请使用GetFields而不是GetProperties.

return from p in obj.GetType().GetFields()
       where p.FieldType == typeof(T)
       select new KeyValuePair<string, T>(p.Name, (T)p.GetValue(obj));

我建议您将字段更改为所有属性。


推荐阅读