Why can I not assign a List of concrete types to a List of that concrete's interface?

前端 未结 8 1503
悲哀的现实
悲哀的现实 2020-12-19 02:17

Why does this not compile?

public interface IConcrete { }

public class Concrete : IConcrete { }

public class Runner
{
    public static void Main()
    {
         


        
8条回答
  •  一向
    一向 (楼主)
    2020-12-19 02:56

    Almost all these answers say that this will be supported in C# 4. They are all wrong.

    Just to be crystal clear: this is not an example of covariance that we will be supporting in C# 4, because doing so would not be typesafe. We are supporting typesafe covariance and contravariance of generic interfaces and delegates which are constructed with reference type arguments. The example here uses a class type, List, not an interface type. And the interface type, IList, is not typesafe for covariance or contravariance.

    IEnumerable will be covariant, as it is an interface that is safe for covariance.

提交回复
热议问题