泛型问题 - C# 3.0
我有一个问题:
class Base
{
}
class DerivedClass : Base
{
}
class Test<T> where T : Base
{
}
像这样:
Test
我认为 C# 4.0 中有一种解决方法,但是有没有办法在 C# 3 中做类似的事情?
I have a problem:
class Base
{
}
class DerivedClass : Base
{
}
class Test<T> where T : Base
{
}
and something like so:
Test<Base> a = new Test<DerivedClass>();
I think there's a way around it in C# 4.0, but is there a way to do something like so in C# 3?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
简短的回答:不,没有办法。
长答案:不,在 C# 3.0 和 C# 4.0 中都没有办法,因为 C# 3.0 根本不支持协变和逆变,并且仅在 C# 4.0 中的委托类型和接口上支持。
更新:
如果您想将此类的多个实例保存在列表中,而与
T
的具体类型无关,则一种解决方法可能如下所示:创建一个接口
ITest
,在任何需要使用T
的地方都使用Base
。让Test
实现该接口,并通过使用显式接口实现来隐藏ITest
中的方法。使用ITest
作为方法的参数类型。示例代码:
如果您只想将该类传递给方法而不需要特定的
T
,您也可以使您的方法通用:Short answer: No, there is no way.
Long answer: No, there is no way in neither C# 3.0 nor C# 4.0, because co- and contravariance is not supported in C# 3.0 at all and only on delegate types and interfaces in C# 4.0.
UPDATE:
If you want to save several instances of this class in a list, independent of the concrete type of
T
, one workaround could look like this:Create an interface
ITest
that usesBase
everywhere you would useT
. MakeTest<T>
implement that interface and hide the methods fromITest
by using explicit interface implementation. UseITest
as parameter type to your method.Sample code:
If you just want to pass that class to a method without requiring a specific
T
, you can make your method generic as well:这就是您想要的协变,除了使用强制转换之外,C# 3.0 中没有太多解决办法。
即使
DerivedClass
继承自Base
,Test
也不会从Test
继承。That's covariance you want and there isn't much of a way round in C# 3.0, other than using casting.
A
Test<DerivedClass>
does not inherit from aTest<Base>
even ifDerivedClass
inherits fromBase
.