c# - 获取基类的 IEnumerable 中子类的属性

标签 c# reflection

如果我有给定实体的集合,我就能够获取实体的属性,如下所示:

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/

相关文章:

java - final 以某种方式导致静态行为

java - 使用反射实例化内部类时出现 InstantiationException。为什么?

Java 字节码操作和 Java 反射 API?

c# - 传递匿名函数而不是连接事件

c# - 在查询之前构建 LINQ 表达式

c# - WPF WF4.5 Rehosted Designer 内存问题

scala - 使用 Scala 反射查找派生最多的运行时类型

c# - 在 Excel 中使用剪贴板复制粘贴(VSTO 代码)会卡住其他 Microsoft Office 应用程序

c# - 如何在c#中将字符串添加到数组列表

reflection - 在 Golang 中将值类型转换为 Map?