如果我有给定实体的集合,则可以像下面这样获取实体的属性:
var myCollection = new List<Foo>();
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();
即使使用基类声明了集合,是否仍然可以获得集合中项目的类型?
最佳答案
这是因为您是从由类型参数T
表示的类型(即Foo
)获得属性的,而Foo
仅具有One
属性。
为了获得所有可能的属性,您需要像这样遍历列表中所有对象的类型:
var allProperties = fooCollection
.Select(x => x.GetType())
.Distinct()
.SelectMany(t => t.GetProperties())
.ToList();