我目前正在使用此代码获取对象中的所有变量并将数据放在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)
提前致谢.