为什么 IList<T> 实现了 IEnumerable<T> 和 ICollection<T> 而 ICollection<T> 本身实现了 IEnumerable<T>

Why does IList<T> implement IEnumerable<T> and ICollection<T> while ICollection<T> itself implements IEnumerable<T>

为什么IList是这样定义的?

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

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

public interface IEnumerable<T> : IEnumerable

难道就这样吗

public interface IList<T> : ICollection<T>

所以,为了测试我创建了这些接口,只是为了确定它是否有效!

public interface IOne
{
    string One();
}

public interface ITwo : IOne
{
    string Two();
}

public interface IThree : ITwo, IOne
{
    string Three();
}

虽然它非常好,但 Resharper 抱怨 "Redundant interfaces"。

知道微软为什么要继续这个实现吗?

接口 "inheritance" 是软件工程中最具误导性的术语之一。你没有继承 squat,接口没有任何实现,所以你也不能继承它。您只需继承需求即可实现方法。

通过重复接口声明来添加该需求不会改变任何内容,您已经有需求并且添加额外的需求没有任何区别。因此,既然这无关紧要,Microsoft 只是有用地重复了接口,这样您就可以一口气知道哪些接口是由 List 实现的。您不必深入到接口声明就可以看到 List 也实现了 IEnumerable。这是一种自我记录的编码风格,推荐。

请注意这枚勋章的另一面,仅需 单个 方法实现即可实现具有完全相同方法的两个不同接口。虽然这通常很有用,但有时这并不是您想要的。比方说,ICowboy 和 IPainter,它们都有一个 Draw() 方法。它不应该做同样的事情 :) 然后您必须回退到显式实现以避免歧义。

解决 Resharper 投诉,这当然不是很有帮助。 Resharper 倾向于假设程序员最坏的情况。但是如果你想关闭它那么你需要从 IThree 继承列表中删除 IOne,这是多余的。对于实现 IThree 的 class 也是一样,您还需要从继承列表中删除 ITwo 和 IOne。或者只是关闭警告。