为什么可以在基类中实现接口方法?(Why is it possible to implement an interface method in base class? [duplicate])

编程入门 行业动态 更新时间:2024-10-04 11:27:50
为什么可以在基类中实现接口方法?(Why is it possible to implement an interface method in base class? [duplicate])

这个问题已经在这里有一个答案:

为什么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 answers

In 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 */ }

更多推荐

本文发布于:2023-08-07 11:03:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464092.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类中   接口   方法   implement   interface

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!