Перебор свойств класса и создание простого Объекта, объединяющего информацию - PullRequest
1 голос
/ 10 июля 2020

У меня есть следующий класс

 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 property! = ""

Я пробовал перебирать свойства

 foreach (var prop in report.scan_results.scan_details.GetType().GetProperties())
 {
     Console.WriteLine("{0} = {1}", prop.Name, prop.GetValue("threat_found", null));
 }

Но я продолжаю получать следующее исключение -> Объект не соответствует желаемому типу

Ответы [ 2 ]

0 голосов
/ 11 июля 2020

Ваша проблема здесь:

prop.GetValue ("dangerous_found", null)

Вы пытаетесь получить свойство «Lavasoft» из строки «dangerous_found» с нулевым индексом.

Это работает:

        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}");
        }
0 голосов
/ 11 июля 2020

попробуйте это:

public class ScanDetail
{
    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; }
}

public class ScanDetails
 {
    public ScanDetail Lavasoft { get; set; }
    public ScanDetail STOPzilla { get; set; }
    public ScanDetail Zillya { get; set; }
    public ScanDetail VirusBlokAda { get; set; }
    public ScanDetail TrendMicro { get; set; }
    public ScanDetail SUPERAntiSpyware { get; set; }
    public ScanDetail nProtect { get; set; }
    public ScanDetail NANOAV { get; set; }
 }


 foreach (var prop in report.scan_results.scan_details.GetType().GetProperties())
 {
    if(prop.PropertyType is ScanDetail)
    {
        var scan_detail = prop.GetValue(report.scan_results.scan_details) as ScanDetail;
        Console.WriteLine("{0}.{1} = {2}", prop.Name, "threat_found", scan_detail.threat_found);    
    }
    
 }
...