我没有参加PDC 2008,但我听到一些消息称C#4.0被宣布支持Generic协方差和反差异.也就是说,List<string>可以分配给List<object>.怎么会这样?
在Jon Skeet的C#深度书中,解释了为什么C#泛型不支持协方差和反方差.它主要用于编写安全代码.现在,C#4.0改为支持它们.它会带来混乱吗?
有人知道有关C#4.0的细节可以给出一些解释吗?
给出以下类型:
public interface IPrimary{ void doBattle(); }
// an ISecondary "is" an IPrimary
public interface ISecondary : IPrimary { }
// An implementation of ISecondary is also an IPrimary:
internal class SecondaryImpl : ISecondary
{
// Required, since this is an IPrimary
public void doBattle(){ }
}
Run Code Online (Sandbox Code Playgroud)
为什么我不这样做?
List<IPrimary> list = new List<ISecondary>();
Run Code Online (Sandbox Code Playgroud)
这会导致以下编译错误:
参数类型'System.Collections.Generic.List'的参数类型不可分配给参数类型'System.Collections.Generic.List'
我理解错误,我意识到有一些解决方法.我只是没有看到任何明确的原因,为什么不允许这种直接转换.包含在列表中的值ISecondary,应毕竟是(通过扩展)类型的值IPrimary然后被.为什么List<IPrimary>和List<ISecondary>被解释为不相关的类型?
任何人都可以清楚地解释C#以这种方式设计的原因吗?
一个稍微扩展的例子:我在尝试执行类似以下操作时遇到了这个问题:
internal class Program
{
private static void Main(string[] args)
{
// Instance of …Run Code Online (Sandbox Code Playgroud)