作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
考虑下面的一段代码:
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>
什么是 T
在 A<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/
我是一名优秀的程序员,十分优秀!