这个问题已经在这里有一个答案:
为什么C#中的基类允许实现接口契约而不继承它? 2答案在我的项目中,我发现一个奇怪的情况,似乎在C#中完全有效,因为我没有编译时错误。
简化的例子如下所示:
using System; using System.Collections.Generic; namespace Test { interface IFoo { void FooMethod(); } class A { public void FooMethod() { Console.WriteLine("implementation"); } } class B : A, IFoo { } class Program { static void Main(string[] args) { IFoo foo = new B(); foo.FooMethod(); } } }这样的代码编译。 但是请注意, A不是IFoo , B不实现IFoo方法。 在我的情况下,意外(重构后), A具有相同签名的方法。 但是为什么A知道如何实现IFoo界面的FooMethod ? A甚至不知道IFoo存在。
对我来说这样的设计是危险的。 因为每次实现一些接口,我应该检查这个接口中的每个方法是否与基类方法“干扰”。
如果这是“纯C#功能”? 这叫什么? 我错过了什么吗?
This question already has an answer here:
Why is a base class in C# allowed to implement an interface contract without inheriting from it? 2 answersIn my project I've found a strange situation which seems completely valid in C#, because I have no compilte-time errors.
Simplified example looks like that:
using System; using System.Collections.Generic; namespace Test { interface IFoo { void FooMethod(); } class A { public void FooMethod() { Console.WriteLine("implementation"); } } class B : A, IFoo { } class Program { static void Main(string[] args) { IFoo foo = new B(); foo.FooMethod(); } } }Such code compiles. However, note that A is not IFoo and B doesn't implement IFoo methods. In my case, by accident (after refactoring), A has the method with the same signature. But why should A know how to implement the FooMethod of the IFoo interface? A even doesn't know that IFoo exist.
For me having such design is dangerous. Because every time I implement some interface I should check if each method in this interface "interferes" with the base class methods.
If this is "pure C# feature"? What is it called? Am I missing something?
最满意答案
对于接口中的每个成员,编译器只需要查找一个显式实现(如果有的话),然后查找一个公共实现( 隐式实现),即在公共API上匹配接口签名的方法。 在这种情况下, A.FooMethod()看起来像一个公共实现的精细匹配。 如果B对该选择不满意,可以使用new的方法,或者使用明确的实现; 后者将是首选:
void IFoo.FooMethod() { /* explicit implementation */ }For each member in the interface, the compiler simply looks for an explicit implementation (if one), then a public implementation (implicit implementation), i.e. a method on the public API that matches the interface signature. In this case, A.FooMethod() looks like a fine match for a public implementation. If B wasn't happy with that selection, it could either new the method, or use an explicit implementation; the latter would be preferred:
void IFoo.FooMethod() { /* explicit implementation */ }更多推荐
发布评论