将其转换为泛型基类失败 [英] Casting to Generic base class failing
问题描述
我无法理解为什么我试图转换为泛型基类不工作。
代码的基本结构如下。
接口ICmd
{
}
类上下文
{
}
class Cmd< TContext> :ICmd
TContext:Context
{
}
class MyContext:Context
{
}
class MyCmd:Cmd< MyContext>
{
}
现在我有一个ICmd实例,将它转换为Cmd,如下所示:
var base = cmd as Cmd< Context>
在执行此行后base始终为空。
$ b $
var base = cmd as Cmd< MyContext> b 改变转换只针对上下文而定。 - 这个作品?
希望我已经提供了足够的信息,这是一个协变变量问题吗?$ / $>
谢谢
您可能想要使用共同与反变化。
问题在于 Cmd< Context>
不是 Cmd< / base>的基类; MyContext>
。
有关更详细的答案,请参阅最近的问题: C#泛型继承问题
I am failing to see why my attempt to cast to a generic base class is not working.
The basic structure of the code is as follows.
interface ICmd
{
}
class Context
{
}
class Cmd<TContext> : ICmd
where TContext : Context
{
}
class MyContext : Context
{
}
class MyCmd : Cmd<MyContext>
{
}
So now I have an instance of ICmd and want to cast it to Cmd as follows
var base = cmd as Cmd<Context>
base is always null after this line is executed.
changing cast to be specific for the context only and it works.
var base = cmd as Cmd<MyContext> -- this works ???
Hope I have provided enough information, is this a covariance\contravariance issue?
Thanks
You may want to use co- and contravariance.
The problem is that Cmd<Context>
is not the base class of Cmd<MyContext>
.
See this recent question for a more detailed answer: C# Generics Inheritance Problem
这篇关于将其转换为泛型基类失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!