假设我们有一个嵌套的泛型类:
public class A<T> {
public class B<U> { }
}
这里,typeof(A<int>.B<>)
本质上是一个具有两个参数的泛型类,其中只有第一个被绑定。
如果我有一个带有两个参数的类
public class AB<T, U> { }
有没有办法提到“AB
保持T=int
开放U
”?如果不是,这是 C# 限制还是 CLR 限制?
显然它不能在 C# 中完成,您必须指定两个类型参数,或者一个都不指定。
而且CLR似乎也不支持它,A<int>.B<>
并且A<string>.B<>
引用相同的类型:
Type t1 = typeof(A<int>).GetNestedType("B`1");
Type t2 = typeof(A<string>).GetNestedType("B`1");
// t1.Equals(t2) is true
两种类型的封闭类型都是A<>
(开放泛型类型)
编辑:进一步的测试表明它typeof(A<int>.B<string>)
实际上是 arity 2 的泛型类型,而不是arity 1 的嵌套泛型类型...返回一个带有andtypeof(A<int>.B<string>).GetGenericArguments()
的数组。所以实际上等同于,不支持(泛型类型不能部分关闭)typeof(int)
typeof(string)
typeof(A<int>.B<>)
(A.B)<int, >
这是你的想法吗?
class AB<T, U>
{
protected T t;
U u;
}
class C<U> : AB<int, U>
{
public void Foo()
{
t = 5;
}
}