C#中接口的等效Java 1.6 @Override

Bri*_*128 15 c# java overriding interface

这个问题给出了Java的@Override override在方法上具有C#等价关键字的答案.但是,从Java 1.6开始,@ Override注释也可以应用于接口.

实际使用的是,在Java中,当一个类声称它实现了一个接口方法时(例如,如果删除了接口方法),就会遇到编译错误.C#中有相同的功能吗?

一些代码示例:

Java的:

public interface A {
  public void foo();
  // public void bar(); // Removed method.
}

public class B implements A {
  @Override public void foo();
  @Override public void bar(); // Compile error
}
Run Code Online (Sandbox Code Playgroud)

C#:

public interface IA {
  void Foo();
  // void Bar(); // Removed method.
}

public class B : A {
  public override void Foo(); // Doesn't compile as not 'overriding' method
  public void Bar(); // Compiles, but no longer implements interface method
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*Jon 8

类似的功能:显式接口实现.

public interface IA { 
  void foo(); 
  // void bar(); // Removed method. 
} 

public class B : IA { 
  void IA.foo() {}
  void IA.bar() {} // does not compile
} 
Run Code Online (Sandbox Code Playgroud)

问题是,如果你这样做,你不能通过this指针(从类内部)或通过计算结果的表达式调用方法B- 现在需要转换为IA.

您可以通过创建具有相同签名的公共方法并将调用转发到显式实现来解决此问题,如下所示:

public class B : IA { 
  void IA.foo() { this.foo(); }
  public void foo() {}
} 
Run Code Online (Sandbox Code Playgroud)

然而,这并不是很理想,我从未在实践中看到它.