为什么我不能具体类型的列表分配给具体的接口的列表?

为什么我不能具体类型的列表分配给具体的接口的列表?

问题描述:

为什么这个不能编译?

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) { }

}

和什么是要获得 myList中,以正确的类型?

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

编辑
我搞砸DoStuffWithInterfaceList例如

EDIT I messed up the DoStuffWithInterfaceList example

接受的解决方案是相当低效大名单,和完全不必要的。你可以改变你的方法的签名非常轻微,以使代码工作的没有的任何转换,无论是隐性或显性的:

The accepted solution is quite inefficient for large lists, and completely unnecessary. You can change the signature of your method ever so slightly to make the code work without any conversions, either implicit or explicit:

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

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

注意,该方法是目前通用的,使用一个类型约束,以确保它可以只有 IConcrete 亚型列表来调用。

Notice that the method is now generic and uses a type constraint to ensure that it can only be called with lists of IConcrete subtypes.