【问题标题】:confusion why interface has been inherited again when the base interface already inherits it混淆为什么当基本接口已经继承了接口时,接口又被继承了
【发布时间】:2014-08-16 04:17:12
【问题描述】:

我正在审查继承,对继承接口有些困惑。我们以List<T>为例。

我有这个基本声明:

List<string> categoryList = new List<string>();

当我在光标位于List 时单击Go to Definition,它会显示此代码,

public class List<T> : IList<T>, ICollection<T>, IList, ICollection, 
                       IReadOnlyList<T>, IReadOnlyCollection<T>, 
                       IEnumerable<T>, IEnumerable
{

}

如果我在光标位于IList&lt;T&gt; 上时再次单击Go to Definition

public interface IList<T> : ICollection<T>, IEnumerable<T>, IEnumerable
{

}

现在我的问题是:为什么List&lt;T&gt; 仍然继承ICollection&lt;T&gt;IEnumerable&lt;T&gt;IEnumerableIList&lt;T&gt; 已经继承了它?

【问题讨论】:

    标签: c# oop interface


    【解决方案1】:

    我相信这正是 Visual Studio 表示定义的方式,它向您展示了整个界面层次结构。

    如果你查看Reference Source for List<T>,你会看到它只实现了IListSystem.Collections.IListIReadOnlyList,因为实现 IEnumerable 将是多余的。

    public class List<T> : IList<T>, System.Collections.IList, IReadOnlyList<T>
    {
        // bla bla bla
    }
    

    【讨论】:

    • +1 如果你看到ICollection 接口,它会再次被IEnumarable 继承。
    【解决方案2】:

    这显然是为了便于阅读。只需指定三个接口,代码就可以正常编译:

    public class List<T> : IList<T>, IList, IReadOnlyList<T>
    {
    
    }
    

    但这样一来,你必须知道,IList 继承了ICollectionIEnumerableIList&lt;T&gt; 实现了ICollection&lt;T&gt;IEnumerable&lt;T&gt;,而IReadOnlyList&lt;T&gt; 继承了IReadOnlyCollection&lt;T&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-10
      • 2012-06-10
      • 1970-01-01
      • 1970-01-01
      • 2010-09-21
      • 2015-10-12
      相关资源
      最近更新 更多