我正在尝试这样做:
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>
之间进行转换时看到过这样的协方差问题,但我不认为它适用于像这样的简单泛型。
为了让这个角色发挥作用,有什么好的工作要做?我该如何解决这个问题?
发布于 2011-08-11 23:15:50
interface IA
{
}
class A : IA
{
}
interface IFoo<T> where T : IA
{
}
class Foo<T> : IFoo<T> where T : IA
{
}
class Program
{
static void Main(string[] args)
{
IFoo<A> fooA = new Foo<A>();
Foo<IA> fooIa = fooA as Foo<IA>;
}
}
发布于 2012-05-11 12:58:54
很抱歉,这是用java编写的,但是你可以这样做:
interface Alpha
{
}
class Beta implements Alpha
{
}
class Foo<T>
{
}
class Program
{
static void main(string[] args)
{
Foo<Beta> fooBeta = new Foo<Beta>();
Foo<? implements Alpha> fooAlpha = fooBeta;
}
}
这并不能完全解决问题,但你至少可以在不知道Beta的情况下访问所有的Alpha方法。
https://stackoverflow.com/questions/7028347
复制相似问题