问题描述
我试图使用C#4.0开发Silverlight 4应用程序。
我有这样的情况:
I am trying to develop a Silverlight 4 application using C# 4.0.I have a case like this:
public class Foo<T> : IEnumerable<T>
{
....
}
/ p>
Elsewhere:
public class MyBaseType : MyInterface
{
...
}
和我遇到问题的用法:
Foo<MyBaseType> aBunchOfStuff = new Foo<MyBaseType>();
Foo<MyInterface> moreGeneralStuff = myListOFStuff;
现在我相信这在C#3.0是不可能的,因为通用类型是不变的。但是我认为这是可能的在C#4.0通过新的协方差的泛型技术?
Now I believe this was impossible in C# 3.0 because generic type were "Invariant". However I thought this was possible in C# 4.0 through the new covariance for generics technology?
根据我的理解,在C#4.0很多常见的接口被修改以支持方差。在这种情况下,我的 Foo
类需要什么特别的才能变成协变的?
As I understand it, in C# 4.0 a lot of common interfaces (like IEnumerable) have been modified to support variance. In this case does my Foo
class need to anything special in order to become covariant?
Silverlight 4(RC)?
And is covariance supported in Silverlight 4 (RC) ?
推荐答案
协调性仅支持接口和代理:
Covariance is only supported for Interfaces and Delegates:
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;
重要的是 out
接口 Foo
。
这篇关于C#4.0 RC,Silverlight 4.0 RC协方差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!