如何使用反射来获取对象中的所有变量?

Myt*_*de_ 2 c# reflection dictionary

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

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

在此代码中,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));
}
Run Code Online (Sandbox Code Playgroud)

当我测试我的字典中的任何数据时,没有值(我使用Visual Studio的调试内容来检查,我的程序也打印出字典中的所有数据 - 当然,不存在).请告诉我我在这里做的错误(我还在学习编码,我在发帖时已经15岁了).

编辑:这就是propertiesJSON的样子

var propertiesJSON = Newtonsoft.Json.JsonConvert.DeserializeObject<Models.PropertiesJSON>(content);
Run Code Online (Sandbox Code Playgroud)

这是班级本身:

class PropertiesJSON
{
    public string botToken;
    public bool girl;
    public int age;
    public string[] hi;
    public string test;
}
Run Code Online (Sandbox Code Playgroud)

提前致谢.

Swe*_*per 6

那些不是属性!

这些:

public string botToken;
public bool girl;
public int age;
public string[] hi;
public string test;
Run Code Online (Sandbox Code Playgroud)

是所有领域.如果它们是属性,它们看起来像这样:

public string botToken { get; }
public bool girl  { get; }
public int age  { get; }
public string[] hi  { get; }
public string test  { get; }
Run Code Online (Sandbox Code Playgroud)

要获取字段,请使用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));
Run Code Online (Sandbox Code Playgroud)

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