【问题标题】:Item type from a list type c# [closed]来自列表类型c#的项目类型[关闭]
【发布时间】:2018-05-27 13:12:52
【问题描述】:

我有一个类型变量,它是某种类型的列表。假设我不知道商品类型,如何获取商品类型?

类似

...
var type = property.PropertyType;

if (type == typeof(List<>) // I know this doesn't work
{ do something }
...

编辑:我什至试过type is Ilisttype.IsGenericType,结果都是假的。

即使只是尝试

var a = (new List<int>()).GetType(); 

if ( a.IsGenericType && a is IList){} //  both conditions return false

我不知道我做错了什么。

【问题讨论】:

  • 我已经尝试了很多东西,但都不适合我。
  • var itemType = type.GetElementType();结果为空
  • Type itemType = type.GenericTypeArguments.First();
  • @Don'tmindme 首先,我建议编辑您的问题并使用您尝试 GetType() 的实际代码更新它。您在问题中显示一件事,但评论显示别的东西。

标签: c# list types


【解决方案1】:

根据我的理解,您想检查类型是否为列表以及列表的元素是否为 X 类型。

您可以执行以下操作:

        var type = (new List<int>()).GetType();

        if (type.GetInterface("IList") != null && type.IsGenericType
                && type.GenericTypeArguments.Length == 1
                && type.GenericTypeArguments[0] == typeof(int))
                    Console.WriteLine(true); //Outputs True

【讨论】:

  • 没错。我试过type is Ilisttype.IsGenericType,结果都是假的。即使只是简单地尝试使用var a = (new List&lt;int&gt;()).GetType(); 并询问a.IsGenericTypea is IList 也会导致错误。我不知道我做错了什么。
  • type.GenericTypeArguments.Length == 1type.GenericTypeArguments[0] == typeof(int)) 是真的……
  • @Don'tmindme 已更新和测试。
猜你喜欢
  • 2017-01-28
  • 1970-01-01
  • 2020-12-25
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多