c# - 为什么开放泛型的基类型不开放?

标签 c# reflection

考虑下面的一段代码:

public class A<T> { }

public class B<T> : A<T> { }

在这种情况下:

var a = typeof(A<>).GenericTypeArguments.Length;

a 的值为 0,这并不奇怪。然而,这对我来说有点出乎意料:

var b = typeof(B<>).BaseType.GenericTypeArguments.Length;

其中 b 的值为 1。因此它使用不存在的类型名称“T”关闭,并且仅对其执行 GetGenericTypeDefinition 使其再次打开。这是为什么?

最佳答案

So it is closed using a non-existing type of name "T" and only doing GetGenericTypeArgument on it makes it open again. Why is that?

因为 提供了一个类型参数 - B 的类型参数.

看看你是如何指定基类的:

public class B<T> : A<T>

什么是 TA<T>如果它不是类型参数?仅仅因为类型参数本身是类型参数并不意味着它没有被指定为类型参数。

考虑一下:

public class A<T1, T2> { }

public class B<T> : A<T, int> { }

在这里,B<T> 的基类是A<T, int> - 你可以确定 int已通过询问类型参数指定。您还可以显示 T 在哪里来自:

using System;
using System.Reflection;
using System.Collections.Generic;

public class A<T1, T2> { }

public class B<T> : A<T, int> { }

class Program
{
    static void Main()
    {
        var bT = typeof(B<>).GetTypeInfo().GenericTypeParameters[0];
        var listT = typeof(List<>).GetTypeInfo().GenericTypeParameters[0];
        var bBaseArguments = typeof(B<>).BaseType.GenericTypeArguments;
        Console.WriteLine(bBaseArguments[0] == bT); // True
        // Shows that the T from B<T> isn't the same as the T from List<T>
        Console.WriteLine(bBaseArguments[0] == listT); // False
        Console.WriteLine(bBaseArguments[1] == typeof(int)); // True
    }
}

关于c# - 为什么开放泛型的基类型不开放?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32091197/

相关文章:

c# - 如果仅缺少一个值,DataContractSerializer 反序列化将完全失败

c# - 如何避免重复的接口(interface)代码?

c# - 实现接口(interface)和匹配属性的 MEF 加载类型

c# - GetType 返回 Int 而不是 System.Int32

c# - 如何创建不同类型的数组

c# - 从 C# 托管代码调用 win32 CreateProfile()

java反射问题

java - 如何声明 getParameterTypes() 返回类型的变量?

java - 如何通过反射以所需/正确的顺序调用方法

c# - 使用正则表达式从字符串中删除标点符号