首页 > 解决方案 > 遍历类的属性并创建一个简单的对象合并信息

问题描述

我有以下课程

 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));
 }

但我不断收到以下异常-> 对象与所​​需类型不匹配

标签: c#.netclasspropertiesienumerable

解决方案


你的问题在这里:

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}");
        }

推荐阅读