C# 4.0 RC、Silverlight 4.0 RC 协方差
我正在尝试使用 C# 4.0 开发 Silverlight 4 应用程序。 我有一个这样的案例:
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) 是否支持协方差?
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>
{
....
}
Elsewhere:
public class MyBaseType : MyInterface
{
...
}
And the usage where I am having problems:
Foo<MyBaseType> aBunchOfStuff = new Foo<MyBaseType>();
Foo<MyInterface> moreGeneralStuff = myListOFStuff;
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?
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?
And is covariance supported in Silverlight 4 (RC) ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要指示接口或委托的泛型类型参数在
T
中是协变的,您需要提供out
关键字。然而,目前这对于班级来说是不可能的。我建议创建一个具有协变泛型类型参数的接口,并让您的类实现它。
至于 Silverlight 4 中的协方差支持:在测试版中不支持它,我需要检查他们是否在候选版本中实现了它。编辑:显然是这样。
编辑2:,<代码>操作,<代码>功能,...)。
由于 BCL 中的某些类型没有设置适当的泛型类型修饰符 (
IEnumerable
IEnumerableSilverlight 5 解决了这些问题:http://10rem.net/blog/2011/09/04/the-big-list-of-whats-new-or-improved-in-silverlight-5
SL4编译器但是确实支持
in
和out
修饰符。以下编译并按预期工作:To indicate that the generic type parameter of an interface or delegate is covariant in
T
, you need to supply theout
keyword.However this is currently not possible for classes. I suggest to create an interface with a covariant generic type parameter, and let your class implement it.
As for covariance support in Silverlight 4: In the beta's it wasn't supported, I would need to check if they have implemented it in the release candidate. Edit: Apparently it is.
Edit2:
There may be some confusion whether SL4 actually supports co- and contravariance for interfaces and delegates, due to the fact that some of the types in the BCL don't have the appropriate generic type modifiers set (
IEnumerable<T>
,Action<T>
,Func<T>
, ...).Silverlight 5 addresses these issues: http://10rem.net/blog/2011/09/04/the-big-list-of-whats-new-or-improved-in-silverlight-5
The SL4 compiler does however support the
in
andout
modifiers. The following compiles and works as expected:仅接口和委托支持协变:
重要的是接口
Foo
上的out
关键字。Covariance is only supported for Interfaces and Delegates:
Important is the
out
-Keyword on the InterfaceFoo
.