协变、逆变和消除多余的类型参数
给定以下类层次结构:
abstract class A { }
abstract class B { }
abstract class C { }
abstract class D<TA, TB, TC>
where TA : A
where TB : B
where TC : C { }
class E : A { }
class F : B { }
class G : C { }
class H : D<E, F, G> { }
我想创建一个简单的泛型方法来实例化 D
类型的对象:
void Create<TD>(string description)
where TD : D
{
var instance = Activator.CreateInstance<TD>();
}
但是编译器强制指定 D
的类型参数,因此我必须写以下内容:
void Create<TD, TA, TB, TC>(string description)
where TA : A
where TB : B
where TC : C
where TD : D<TA, TB, TC>
{
var instance = Activator.CreateInstance<D>();
}
这意味着我不能写,而是
Create<H>("foo");
必须写
Create<H, E, F, G>("foo");
我的问题是:既然我指定 H
作为具体实例,为什么编译器需要附加类型方法签名上基类 D
的参数?为什么它不能简单地从 H
推断出那些?
Given the following class hierarchy:
abstract class A { }
abstract class B { }
abstract class C { }
abstract class D<TA, TB, TC>
where TA : A
where TB : B
where TC : C { }
class E : A { }
class F : B { }
class G : C { }
class H : D<E, F, G> { }
I want to create a simple generic method to instantiate an object of type D
:
void Create<TD>(string description)
where TD : D
{
var instance = Activator.CreateInstance<TD>();
}
But the compiler forces the type parameters for D
to be specified, hence I have to write the following:
void Create<TD, TA, TB, TC>(string description)
where TA : A
where TB : B
where TC : C
where TD : D<TA, TB, TC>
{
var instance = Activator.CreateInstance<D>();
}
Which means that instead of being able to write
Create<H>("foo");
I have to write
Create<H, E, F, G>("foo");
My question is: since I'm specifying H
as the concrete instance, why does the compiler require the additional type parameters for the base class D
on the method signature? Why can't it simply infer those from H
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
其中 TD : D
暗示 D 不是泛型,而 as whereTD : D
暗示 D 是泛型。where TD : D
implies D is not generic, where as where whereTD : D<TA, TB, TC>
implies that D is generic.