【问题标题】:How to determine if an unknown type is a List<T> and what type T is [duplicate]如何确定未知类型是否为 List<T> 以及 T 是什么类型 [重复]
【发布时间】:2016-02-13 13:47:13
【问题描述】:

我正在尝试提取未知属性的类型并确定它是否为List&lt;T&gt;,以及T 是否属于特定类型。

我了解如何使用反射来确定属性的类型,但是我不知道如何确定属性是否为 List&lt;T&gt; 以及 T 是什么类型。希望大家帮忙。

编辑:How to get the type of T from a member of a generic class or method? 不太适用。那里的答案假设我知道我的未知类型是List。我已经编辑了我的标题以更清晰。

【问题讨论】:

  • @CompuChip 您可能想稍微扩展一下该评论。也许在答案中显示演示代码,以便 OP 知道要做什么。
  • 还有list.GetType().GetGenericArguments().Single()从这里stackoverflow.com/a/4452598/4767498
  • 我的标题不清楚,我什至不知道类型是否以列表开头。我已经适当地编辑了我的问题和标题。

标签: c# .net reflection


【解决方案1】:
object o = new List<double>();

Type t = o.GetType();

if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(List<>))
    Console.WriteLine("This is a list of type {0}", t.GenericTypeArguments[0].Name);

【讨论】:

  • 如果o 不是泛型类型,则会引发异常。有没有办法检查它是否是泛型类型以避免不得不依赖异常来确定它不是泛型类型?
  • 是的,请参阅更新后的答案
  • 啊!我不知道IsGenericType 谢谢!
猜你喜欢
  • 1970-01-01
  • 2015-06-25
  • 1970-01-01
  • 2010-12-23
  • 2015-04-24
  • 1970-01-01
  • 2018-12-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多