直接实现一个接口和通过另一个接口实现有区别吗?

Is there any difference between directly implementing an interface and implementing it through another?

也就是说,如果我有接口:

public interface Foo { }

public interface Bar { }

public interface Baz : Foo, Bar { }

我有一个 class Qux,是否有任何代码(除了基于确切接口的反射,或者因为一个版本没有实现 Baz) 根据 Qux 是否像这样声明,其功能会有所不同:

public class Qux : Foo, Bar { }

与此相比?

public class Qux : Baz { }

除了 Baz 未实现这一明显差异外,我不知道其他相关差异。

在 C# 规范中(我正在查看 C# 4.0 第 13.4 节,但对于较新的版本它应该仍然适用),它说:

A class or struct that directly implements an interface also directly implements all of the interface's base interfaces implicitly. This is true even if the class or struct doesn't explicitly list all base interfaces in the base class list.

这意味着以下定义是等价的:

public class Qux : Baz {}
public class Qux : Baz, Foo, Bar {}

它甚至可以让您显式实现 Foo 接口方法,即使它没有被显式列为基本接口:

public interface Foo { void FooMethod(); }
public interface Bar { void BarMethod(); }
public interface Baz : Foo, Bar { }
public class Qux : Baz
{
    void Foo.FooMethod() { } // legal
    public void BarMethod() { }
}

所以所有差异应该只与 Baz 接口有关。

如果 Baz 是基础 class 而不是接口,则存在 差异。第 13.4.5 和 13.4.6 节声明派生的 class 不会更改接口映射,除非显式重新实现接口。例如:

public interface Foo { string FooMethod(); }
public class Baz : Foo { public string FooMethod() { return "Baz"; } }
public class Qux : Baz { public new string FooMethod() { return "Qux"; } }

Foo.FooMethodQux 的映射仍然是 Baz.FooMethod:

Foo x = new Qux();
x.FooMethod(); // returns "Baz"

但是如果你这样做了...

public class Qux : Baz, Foo { ... }

...它将重新实现接口,x.FooMethod() 将 return "Qux".

值得注意的是,如果将两者结合起来,比如...

public interface Baz : Foo, Bar {}
public class QuxBase : Baz {}
public class Qux : QuxBase, Baz {}

... 那么 Qux 仍然会像定义为 public class Qux : QuxBase, Baz, Foo, Bar:

一样工作

When a class implement an interface, it implicitly also implements all of that interface's base interfaces. Likewise, a reimplementation of an interface is also implicitly a reimplementation of all of the interface's base interfaces.

所以即使在这种情况下,实施Baz和实施Foo, Bar之间的唯一区别是Baz本身是否被实施。

换句话说,如果您从不使用 Baz 界面本身,我找不到任何区别。