c# - 如何使用反射来获取对象中的所有变量?
问题描述
我目前正在使用此代码来获取对象中的所有变量并将数据放在字典中(键是变量名,值是变量的内容)。
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;
}
提前致谢。
解决方案
那些不是属性!
这些:
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));
我建议您将字段更改为所有属性。
推荐阅读
- oracle - Oracle - 合并/插入语句中的动态 SQL 列名
- sql - 找到 6 个月的差距并抓住一切 之后,如果没有 6 个月的差距,那么就抓住一切
- python - 如何在 Tensorflow 中有效地乘法和 reduce_max?
- delphi - 如何在 Delphi GMLib 中清除 TWebBrowser 中的缓存?
- google-apps-script - 如何将 Google 表格下拉菜单更改为下一个选项?
- c# - 如何正确地大摇大摆地显示十进制值
- java - Swagger-ui 不适用于 jackson-dataformat-xml
- vba - VBA:访问变体/字符串数组值
- spring-boot - 在 kotlin 的构造函数中使用 lateinit 属性
- php - 为什么这会抛出错误的结果?