无法在一般类型之间转换 [英] Cannot cast between generic types

查看:56
本文介绍了无法在一般类型之间转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试这样做:

interface IA
{
}

class A : IA
{
}

class Foo<T> where T: IA
{
}

class Program
{
    static void Main( string[] args )
    {
        Foo<A> fooA = new Foo<A>();
        Foo<IA> fooIA = fooA as Foo<IA>;
    }
}

但是,的演员表Foo< A> Foo< IA> 不会编译。我记得在 List< T> 之间进行转换时看到过这样的协方差问题,但是我不认为它适用于像这样的简单泛型。

However, the cast from Foo<A> to Foo<IA> does not compile. I recall seeing covariance issues like this when casting between List<T>'s, but I didn't think it applied to simple generics like this.

要使此演员表正常工作,有什么好的方法?我该如何解决这个问题?

What is a good work around to getting this cast to work? How do I solve this problem?

推荐答案

所有通用的都是不变的。另一方面,接口(和委托人)可以支持协方差和相反方差,但前提是必须安全地这样做。并且他们需要明确选择加入。

All generic classes are invariant. Interfaces (and delegates) on the other hand can support co- and contra-variance, but only in the cases where it's possible safely. And they need to opt-in explicitly.

例如通过 IFoo< out T> IFoo< in T>

这篇关于无法在一般类型之间转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆