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

前端 未结 8 1515
悲哀的现实
悲哀的现实 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 03:18

    C# does not currently support converting generic types like that (it will be supported in C# 4, if I understand it correctly As wcoenen states in comments below, and Eric also clarifies in his answer, the only way to make it work in C#4 is to use IEnumerable). For now you will need to convert your list in some way.

    You could call the method like this:

    DoStuffWithInterface(myList.ConvertAll(n => n as IConcrete));
    

    Update
    I realized that you probably don't need the cast inside the lambda, even though I sort of like it for clarity. So this should also work:

    DoStuffWithInterface(myList.ConvertAll(n => n));
    

提交回复
热议问题