c# - 使用反射在 IList<T> 中查找 <T>

标签 c# c#-4.0

我正在开发一个项目,我必须通过数据模型进行反射(reflection),以找出数据模型上每个属性的类型。我的代码适用于除通用集合之外的所有情况。我必须能够知道 IList 中的 T 是什么。

我有以下数据模型

public class ArrryOfObjects
{
    public NestModelNestedClass NestClass { get; set; }
    public int IntObject { get; set; }
    public IList<NestModelNestedClass> ListOfObjects { get; set; }
}

我见过几个例子,比如https://stackoverflow.com/a/1043778/136717如何做到这一点,但他们使用 type.GetGenericTypeDefinition()得到类型。但在我的示例中,我无法使用它,因为“type.IsGeneric.Parameter”为 false。

我已查看类型文档,但不明白如何执行此操作。

最佳答案

试试这个:

var t = typeof(ArrryOfObjects)
    .GetProperty("ListOfObjects")
    .PropertyType
    .GetGenericArguments()[0];

它是这样工作的:

  • 来自 ArrryOfObjects 的类型...
  • 获取名为 ListOfObjects 的属性...
  • 获取该属性的类型...
  • 我们知道这是一种至少具有一个类型参数的泛型类型。
  • 我们得到第一个类型参数 - 在您的示例中它应该是 typeof(NestModelNestedClass)

附注GetGenericTypeDefinition为您提供typeof(IList<>) ,其中 IList<NestModelNestedClass> 的泛型类型是一个通用实例。

关于c# - 使用反射在 IList<T> 中查找 <T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8637320/

相关文章:

c# - 使用 IProgress.Report() 报告进度时,控制台消息的显示顺序不正确

C# 从字典中获取键 <string, Stream>

asp.net - 如何实现 Converse.js 用于 asp.net 4.0 网站的 XMPP 聊天客户端

c# - 是否可以从运行的 Quartz.Net 作业调度程序服务中添加或删除作业和触发器?

c#-4.0 - 按契约(Contract)设计/C# 4.0/避免 ArgumentNullException

c#-4.0 - Outlook内存不足异常

c# - 创建特定格式 Json 的正确方法

c# - 为什么在这种情况下编译器不提示?

c# - 对 List<string> 进行排序,如 Excel 列排序

c# - log4net 的文件和数据库多重配置