【问题标题】:How to get typeof(List<>) from typeof(List<T>) by removing generic argument如何通过删除泛型参数从 typeof(List<T>) 获取 typeof(List<>)
【发布时间】:2012-12-26 10:04:14
【问题描述】:

我有 typeof(List&lt;T&gt;) 作为 Type 对象,但我需要 typeof(List&lt;&gt;) 可以从中使用 MakeGenericType() 检索 List 的类型对象,这可能吗?

更新:伙计们,谢谢。这似乎是一个微不足道的问题。但无论如何,我赞成每个人并接受第一个答案。

【问题讨论】:

标签: c# generics


【解决方案1】:

如果我正确地理解了您的问题,您有一个泛型类型 (List&lt;int&gt;) 和另一种类型(比如说long),并且您想要创建一个List&lt;long&gt;。可以这样做:

Type startType = listInt.GetType();   // List<int>
Type genericType = startType.GetGenericTypeDefinition()  //List<T>
Type targetType = genericType.MakeGenericType(secondType) // List<long>

但是,如果您使用的类型确实是列表,那么如果您实际使用它可能会更清楚:

Type targetType = typeof(List<>).MakeGenericType(secondType) // List<long>

【讨论】:

    【解决方案2】:

    您可以使用Type.GetGenericTypeDefinition

    【讨论】:

      【解决方案3】:

      我假设您的意思是实现以下目标?

      var list = new List<int>();
      Type intListType = list.GetType();
      Type genericListType = intListType.GetGenericTypeDefinition();
      Type objectListType = genericListType.MakeGenericType(typeof(object));
      

      【讨论】:

        【解决方案4】:

        答案是 Type.GetGenericTypeDefinition:
        http://msdn.microsoft.com/en-us/library/system.type.getgenerictypedefinition.aspx

        例子:

        var t = typeof(List<string>);
        var t2 = t.GetGenericTypeDefinition();
        

        然后可以这样做:

        var t = typeof(List<>);
        var t2 = t.MakeGenericType(typeof(string));
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-08-24
          • 1970-01-01
          • 1970-01-01
          • 2020-11-15
          • 1970-01-01
          • 1970-01-01
          • 2021-06-16
          • 1970-01-01
          相关资源
          最近更新 更多