为什么我不能具体类型的列表分配给具体的接口的列表? [英] Why can I not assign a List of concrete types to a List of that concrete's interface?

查看:175
本文介绍了为什么我不能具体类型的列表分配给具体的接口的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这个不能编译?

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.

这篇关于为什么我不能具体类型的列表分配给具体的接口的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆