为什么我不能将具体类型列表分配给该具体界面的列表?

Jer*_*eir 8 c#

为什么这不编译?

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

}
Run Code Online (Sandbox Code Playgroud)

什么是将myList设置为正确类型的最快方法?

编辑我弄乱了DoStuffWithInterfaceList示例

Eri*_*ert 18

几乎所有这些答案都说这将在C#4中得到支持.他们都错了.

简单来说:这不是我们将在C#4中支持的协方差的一个例子,因为这样做不会是类型安全的. 我们支持使用引用类型参数构造的泛型接口和委托的类型安全协方差和逆变.这里的示例使用类类型List,而不是接口类型.并且接口类型IList对于协方差或逆变不是类型安全的.

IEnumerable将是协变的,因为它是一个对协方差安全的接口.


Kon*_*lph 12

对于大型列表,接受的解决方案效率非常低,而且完全没有必要.您可以稍微更改方法的签名,以使代码无需任何隐式或显式转换即可运行:

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
    { }
}
Run Code Online (Sandbox Code Playgroud)

请注意,该方法现在是通用的,并使用类型约束来确保只能使用IConcrete子类型列表调用它.