循环通过对象内部的对象

问题描述 投票:0回答:1

我有一个Alarms类,其中包含不同模型的多个Lists。每个模型都不同,它们由多个字符串属性组成。我的目标是为每个模型创建一个CSV文件,但不对模型中的每个字符串属性进行编码。

public class Alarms
{
   public List<SectorA> SectorA { get; set; } = new List<SectorA>();
   public List<SectorB> SectorB { get; set; } = new List<SectorB>();
   public List<SectorC> SectorC { get; set; } = new List<SectorC>();
}

我找到了一种遍历字符串属性的方法,如下所示:

foreach (PropertyInfo prop in alarms.GetType().GetProperties())
{
    var type = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
    if (type == typeof(string))
    {
        line += $"{prop.GetValue(lines, null)};";
    }
}

我的问题是我如何循环通过我的Alarm类以使其在一个循环中获得其内的每个List<SectorX>

编辑:一种SectorX类的示例

public class SectorA
{
    public string Id { get; set; }
    public string Group { get; set; }
    public string Comment { get; set; }
    ...
}
c#
1个回答
0
投票

不是最好的方法,但是

private void Test(object item)
{
    var props = item.GetType().GetProperties();
    foreach (var prop in props)
    {
        object value = prop.GetValue(item);
        if (prop.PropertyType.IsInterface && value != null)
        {
            foreach (var iItem in (System.Collections.IEnumerable)value)
            {
                Console.WriteLine(iItem.ToString());
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.