c# - 遍历类的属性并创建一个简单的对象合并信息
问题描述
我有以下课程
public class ScanDetails
{
public Lavasoft Lavasoft { get; set; }
public STOPzilla STOPzilla { get; set; }
public Zillya Zillya { get; set; }
public VirusBlokAda VirusBlokAda { get; set; }
public TrendMicro TrendMicro { get; set; }
public SUPERAntiSpyware SUPERAntiSpyware { get; set; }
public NProtect nProtect { get; set; }
public NANOAV NANOAV { get; set; }
}
每个子属性都是一个单独的类,像这样
public class Lavasoft
{
public int scan_time { get; set; }
public DateTime def_time { get; set; }
public int scan_result_i { get; set; }
public string threat_found { get; set; }
}
我正在尝试获取其threat_found
属性 !=""的所有类的名称
我试过遍历属性
foreach (var prop in report.scan_results.scan_details.GetType().GetProperties())
{
Console.WriteLine("{0} = {1}", prop.Name, prop.GetValue("threat_found", null));
}
但我不断收到以下异常-> 对象与所需类型不匹配
解决方案
你的问题在这里:
prop.GetValue("threat_found", null)
您正在尝试从索引为 null 的字符串“threat_found”中获取“Lavasoft”属性。
这有效:
foreach (var prop in report.scan_results.scan_details.GetType().GetProperties())
{
var threatFoundPropOfCurrentType = prop.PropertyType.GetProperty("threat_found");
var threatFoundValueOfCurrentType = threatFoundPropOfCurrentType.GetValue(prop.GetValue(report.scan_results.scan_details)) as string;
Console.WriteLine($"{prop.Name} = {threatFoundValueOfCurrentType}");
}
推荐阅读
- c++ - 在 C++ 中打印到控制台的最佳方式是什么?
- python - 折叠连续的线性层
- scala - 如何在scala中设置控制台光标位置?
- javascript - 为外部模块的路由添加路由前缀?
- .net - DevExpress 在设计模式下打开时要求检查 Winforms
- python - 新文件中的 IDLE 自动完成功能不起作用
- c++ - Call not default object constructor for each object uniquely when creating a vector of objects
- python - 如何限制正则表达式不匹配少数实例
- java - 如何对 Java 8 流进行单元测试?
- r - 提高我在 R 中的循环的性能