开发者

Casting to Generic base class failing

I am failing to see why my attempt to cast to a generic base class is 开发者_Python百科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


What you need here is covariance. C# 4 currently does not allow variance for generic type parameters in classes. If your interface doesn't need to allow using the TContext in any input positions, you can consider making the interface generic, and covariant in TContext:

interface ICmd<out TContext> where TContext : Context { }

class Cmd<TContext> : ICmd<TContext> where TContext : Context { }

static void Main(string[] args)
{
    Cmd<MyContext> cmd = new Cmd<MyContext>();

    var foo = cmd as ICmd<Context>;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜