我没有参加PDC 2008,但我听到一些消息称C#4.0被宣布支持Generic协方差和反差异.也就是说,List<string>可以分配给List<object>.怎么会这样?
在Jon Skeet的C#深度书中,解释了为什么C#泛型不支持协方差和反方差.它主要用于编写安全代码.现在,C#4.0改为支持它们.它会带来混乱吗?
有人知道有关C#4.0的细节可以给出一些解释吗?
我怎样才能施放List<object>到List<SomethingElse>?
(已知来自哪里SomethingElseobject)
奖金Chatter
铸造清单:
List<Object> first = ...;
List<SomethingElse> second = (List<SomethingElse>)first;
Run Code Online (Sandbox Code Playgroud)
不起作用:
无法将类型'System.Collections.Generic.List'转换为'System.Collections.Generic.List'
铸造清单:
List<SomethingElse> second = first.Cast<SomethingElse>();
Run Code Online (Sandbox Code Playgroud)
不起作用:
不能将类型'System.Collections.Generic.List'隐式转换为'System.Collections.Generic.List'
我实际上并不需要完整的List<T>对象,只是一个ICollection<T>意志:
ICollection<SomethingElse> second = first;
ICollection<SomethingElse> second = (ICollection<SomethingElse>)first;
ICollection<SomethingElse> second = first.Cast<SomethingElse>();
Run Code Online (Sandbox Code Playgroud)
不工作.