C# 如何在C中使用GetProperties()展平嵌套集合#

C# 如何在C中使用GetProperties()展平嵌套集合#,c#,.net,system.reflection,C#,.net,System.reflection,我有以下对象结构: public class ReportDTO { public string Name { get; set; } public string Identifier { get; set; } public List<DetailsDTO> Details { get; set; } } public class DetailsDTO { public string DetailName { get; set; } pub

我有以下对象结构:

public class ReportDTO
{
    public string Name { get; set; }
    public string Identifier { get; set; }
    public List<DetailsDTO> Details { get; set; }
}

public class DetailsDTO
{
    public string DetailName { get; set; }
    public string DetailAmount { get; set; }
}
但正如我所提到的,我还需要包括
列表详细信息中的属性,因此这些属性需要扁平化

因此,
var properties
应该返回
PropertyInfo[]
和以下值:

[
  {System.String Name}
  {System.String Identifier}
  {System.String DetailName}
  {System.String DetailAmount}
  {System.String DetailName}
  {System.String DetailAmount}
 ...
]
与此相反:

[
  {System.String Name}
  {System.String Identifier}
  {System.Collections.Generic.List`1[...]}  
]

你知道我该怎么做吗?

如果你知道类型,就不需要使用反射:

public static IEnumerable<string> GetValues(ReportDTO dto)
    {
        yield return dto.Name;
        yield return dto.Identifier;
        foreach (var details in dto.Details)
        {
            yield return details.DetailName;
            yield return details.DetailAmount;
        }
    }
公共静态IEnumerable GetValues(ReportDTO到dto)
{
返回dto.Name;
产生返回数据到标识符;
foreach(数据至详细信息中的var详细信息)
{
收益返回详细信息.DetailName;
收益率返回详情。详情金额;
}
}
如果这是几种可能的类型之一,您可以简单地添加检查
If(将数据报告到报告)…
,或者使用或访问者模式。访问者模式的优点是,它允许您将泛型类型限制为特定接口,编译器可以强制访问者处理实现该接口的所有类型,从而提高类型安全性


如果需要处理任何类型的对象,或者希望使用属性来注释属性,则可以使用反射。但这增加了相当多的复杂性,因为对象及其属性形成了需要遍历的图形。您需要处理循环引用和许多其他潜在问题。

什么是
Name
Detail
DetailName
DetailAmount
?它们与属性的关系如何?不确定您的意思是什么?我的意思是,例如,属性中的
DetailName
是什么?我从数据库中获取的一些字符串。看看帖子顶部的类。它仍然不清楚:你正在寻找一种方法来填充
ReportDTO
,或者你已经填充了
ReportDTO
,你需要将其展平?实际上我不知道类型。它应该是完全通用的。因为它将被多个DTO使用。该逻辑将在ExcelService中,该服务基于任何DTO@DiPix在这种情况下,你的问题比问题中所述的要大得多。我会重新考虑这个设计,因为它要么需要大量的工作,要么只为某些特定的类工作。举个例子,如果你递归地遍历所有属性,只选择叶子,你会得到每个字符串的长度列表,可能不是你想要的。检查类似于json.Net的序列化库如何工作。您可以检查属性是否实现IEnumerable,然后枚举其中的所有对象。但请记住,字符串也是可数的!因此,您将迭代每个字符串中的字符,因此您将得到一个空列表,或者一个所有字符的列表。
public static IEnumerable<string> GetValues(ReportDTO dto)
    {
        yield return dto.Name;
        yield return dto.Identifier;
        foreach (var details in dto.Details)
        {
            yield return details.DetailName;
            yield return details.DetailAmount;
        }
    }