我正在尝试使用C# 4.0开发Silverlight4应用程序。我有一个这样的案例:
public class Foo<T> : IEnumerable<T>
{
....
}其他地方:
public class MyBaseType : MyInterface
{
...
}以及我遇到问题的地方的用法:
Foo<MyBaseType> aBunchOfStuff = new Foo<MyBaseType>();
Foo<MyInterface> moreGeneralStuff = myListOFStuff;现在我相信这在C# 3.0中是不可能的,因为泛型类型是“不变的”。然而,我认为通过泛型技术的新协方差,这在C# 4.0中是可能的?
据我所知,在C# 4.0中,许多公共接口(如IEnumerable)已经被修改为支持方差。在这种情况下,我的Foo类是否需要特殊的东西才能成为协变类?
Silverlight 4 (RC)是否支持协方差?
发布于 2010-04-01 14:42:00
仅接口和代理支持协方差:
public interface Foo<out T> { }
public class Bar<T> : Foo<T> { }
interface MyInterface { }
public class MyBase : MyInterface { }
Foo<MyBase> a = new Bar<MyBase>();
Foo<MyInterface> b = a;重要的是接口Foo上的out-Keyword。
发布于 2010-04-01 14:44:09
若要指示接口或委托的泛型类型参数在T中是协变的,需要提供out关键字。
但是,对于类来说,这是不可能的。我建议创建一个具有协变泛型类型参数的接口,并让您的类实现它。
至于Silverlight 4中的协方差支持:在测试版中不支持,我需要检查他们是否在候选版本中实现了协方差支持。编辑:显然是这样的。
Edit2:由于BCL中的一些类型没有设置适当的泛型类型修饰符(IEnumerable<T>,Action<T>,Func<T>,...),因此SL4是否支持接口和委托的协变和逆变可能会有一些混乱。
Silverlight5解决了这些问题:http://10rem.net/blog/2011/09/04/the-big-list-of-whats-new-or-improved-in-silverlight-5
但是,SL4编译器支持in和out修饰符。下面的代码按照预期进行编译和工作:
interface IFoo<out T>
{
T Bar { get; }
}
interface IBar<in T>
{
void Add(T value);
}
delegate void ContravariantAction<in T>(T value);
delegate T CovariantFunc<out T>();https://stackoverflow.com/questions/2558519
复制相似问题