加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 18:26:49 所属栏目:百科 来源:网络整理
导读:给出以下类型: public interface IPrimary{ void doBattle(); }// an ISecondary "is" an IPrimarypublic interface ISecondary : IPrimary { }// An implementation of ISecondary is also an IPrimary:internal class SecondaryImpl : ISecondary{ // Req
给出以下类型:
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>分配编译器是让你摆脱这种麻烦的方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读