How is covariance cooler than polymorphism…and not redundant?

后端 未结 3 984
梦谈多话
梦谈多话 2020-12-31 18:21

.NET 4 introduces covariance. I guess it is useful. After all, MS went through all the trouble of adding it to the C# language. But, why is Covariance more useful than go

3条回答
  •  感情败类
    2020-12-31 18:29

    Consider an API which asks for an IContainer:

    public void DrawShape(IContainer container>) { /* ... */ }
    

    You have a Container. How can you pass your container to the DrawShape API? Without covariance, the type Container is not convertible to IContainer, requiring you to rewrap the type or come up with some other workaround.

    This is not an uncommon problem in APIs that use a lot of generic parameters.

提交回复
热议问题