Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

Why does this not compile?

public interface IConcrete { }

public class Concrete : IConcrete { }

public class Runner
{
    public static void Main()
    {
        var myList = new List<Concrete>();
        DoStuffWithInterfaceList(myList);  // compiler doesn't allow this
    }

    public static void DoStuffWithInterfaceList(List<IConcrete> listOfInterfaces) { }

}

And what's the quickest way to get myList to the correct type?

EDIT I messed up the DoStuffWithInterfaceList example

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...