考虑下面的一段代码:
public class A<T> { }
public class B<T> : A<T> { }
Run Code Online (Sandbox Code Playgroud)
在这种情况下:
var a = typeof(A<>).GenericTypeArguments.Length;
Run Code Online (Sandbox Code Playgroud)
a有价值0,这并不奇怪.然而,这对我来说是出乎意料的:
var b = typeof(B<>).BaseType.GenericTypeArguments.Length;
Run Code Online (Sandbox Code Playgroud)
哪里b有价值1.所以它使用一个不存在的名称"T"关闭,只做GetGenericTypeDefinition它就会再次打开它.这是为什么?
Jon*_*eet 17
因此,它使用不存在的类型名称"T"关闭,并且仅对其执行GetGenericTypeArgument使其再次打开.这是为什么?
因为是提供一种类型的参数-类型参数B.
看看你是如何指定基类的:
public class B<T> : A<T>
Run Code Online (Sandbox Code Playgroud)
什么是T中A<T>,如果它不是一个类型参数?仅仅因为类型参数本身是一个类型参数并不意味着它没有被指定为类型参数.
考虑一下:
public class A<T1, T2> { }
public class B<T> : A<T, int> { }
Run Code Online (Sandbox Code Playgroud)
这里,基类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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1221 次 |
| 最近记录: |