c# – 为什么接口类型的列表不能接受继承接口的意图?

前端之家收集整理的这篇文章主要介绍了c# – 为什么接口类型的列表不能接受继承接口的意图?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
给出以下类型:
public interface IPrimary{ void doBattle(); }

// an ISecondary "is" an IPrimary
public interface ISecondary : IPrimary {  }

// An implementation of ISecondary is also an IPrimary:
internal class SecondaryImpl : ISecondary
{
    // required,since this is an IPrimary
    public void doBattle(){ }
}

为什么我不能这样做?

List<IPrimary> list = new List<ISecondary>();

这导致以下编译错误

Argument type ‘System.Collections.Generic.List’ is not assignable to parameter type ‘System.Collections.Generic.List’

我明白错误,我意识到有解决方法.我只是看不到任何明确的原因,直接转换是不允许的.包含在ISecondary列表中的值应该完全是IPrimary类型的(扩展)值.然后列表< IPrimary>列表< ISecondary>被解释为不相关的类型?

任何人都可以清楚地解释C#设计的原因吗?

一个稍微扩展的例子:我试图做类似以下事情时遇到这个问题:

internal class Program
{
    private static void Main(string[] args)
    {
        // Instance of ISecondary,and by extention,IPrimary:
        var mySecondaryInstance = new SecondaryImpl();

        // This works as expected:
        AcceptImpl(mySecondaryInstance);

        // List of instances of ISecondary,which are also,// by extention,instances of IPrimary:
        var myListOfSecondaries = new List<ISecondary> {mySecondaryInstance};

        // This,however,does not work (results in a compilation error):
        AcceptList(myListOfSecondaries);
    }

    // Note: IPrimary parameter:
    public static void AcceptImpl(IPrimary instance){  }

    // Note: List of type IPrimary:
    public static void AcceptList(List<IPrimary> list){  }

}

解决方法

Why can I not do this? List<IPrimary> list = new List<ISecondary>();

想像你有一个这样定义的方法

public void PopulateList(List<IPrimary> listToPopulate)
{
    listToPopulate.Add(new Primary());  // Primary does not implement ISecondary!
}

如果你要传递一个List< ISecondary>作为参数?

列表< ISecondary>的错误不能从List< IPrimary>分配编译器是让你摆脱这种麻烦的方法.

原文链接:https://www.f2er.com/csharp/96207.html

猜你在找的C#相关文章