无法在一般类型之间转换 [英] Cannot cast between generic types
问题描述
我正在尝试这样做:
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屋!