如果我有给定实体的集合,我就能够获取实体的属性,如下所示:
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
仅具有一个
属性。
要获取所有可能的属性,您需要遍历列表中所有对象的类型,如下所示:
var allProperties = fooCollection
.Select(x => x.GetType())
.Distinct()
.SelectMany(t => t.GetProperties())
.ToList();
关于c# - 获取基类的 IEnumerable 中子类的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38086769/