C# 获取基类的IEnumerable中的子类中的属性

C# 获取基类的IEnumerable中的子类中的属性,c#,reflection,C#,Reflection,如果我有一个给定实体的集合,我可以获得实体的属性,如下所示: var myCollection = new List<Foo>(); entities.GetType().GetGenericArguments()[0].GetProperties().Dump(); var myCollection=newlist(); entities.GetType().GetGenericArguments()[0].GetProperties().Dump(); 但是,如果我的集合是

如果我有一个给定实体的集合,我可以获得实体的属性,如下所示:

var myCollection = new List<Foo>(); 
entities.GetType().GetGenericArguments()[0].GetProperties().Dump();
var myCollection=newlist();
entities.GetType().GetGenericArguments()[0].GetProperties().Dump();
但是,如果我的集合是基类的IEnumerable并填充了派生类,那么列出属性会有一些困难

public class Foo
{
    public string One {get;set;}
}

public class Bar : Foo
{
    public string Hello {get;set;}
    public string World {get;set;}
}

// "Hello", "World", and "One" contained in the PropertyInfo[] collection
var barCollection = new List<Bar>() { new Bar() };
barCollection.GetType().GetGenericArguments()[0].GetProperties().Dump();

// Only "One" exists in the PropertyInfo[] collection
var fooCollection = new List<Foo>() { new Bar() };
fooCollection.GetType().GetGenericArguments()[0].GetProperties().Dump();
公共类Foo
{
公共字符串One{get;set;}
}
公共类酒吧:富
{
公共字符串Hello{get;set;}
公共字符串世界{get;set;}
}
//PropertyInfo[]集合中包含的“Hello”、“World”和“One”
var barCollection=new List(){new Bar()};
barCollection.GetType().GetGenericArguments()[0].GetProperties().Dump();
//PropertyInfo[]集合中只存在“一个”
var fooCollection=new List(){new Bar()};
fooCollection.GetType().GetGenericArguments()[0].GetProperties().Dump();

即使使用基类声明集合,是否仍然可以获取集合中项目的类型?

这是因为您是从类型参数
T
表示的类型中获取属性,该类型参数为
Foo
,并且
Foo
只有
一个属性

要获取所有可能的属性,您需要像下面这样浏览列表中所有对象的类型:

var allProperties = fooCollection
    .Select(x => x.GetType())
    .Distinct()
    .SelectMany(t => t.GetProperties())
    .ToList();

您必须通过迭代而不是编译时信息从实际集合值获取类型。如果列表中有不同类型的对象,该怎么办?你为什么需要这些房子?非常感谢。这就是我一直在寻找的;我感谢你的帮助。