Equivalent of Java 1.6 @Override for interfaces in C#

后端 未结 4 967
慢半拍i
慢半拍i 2021-02-13 03:19

This question gives the answer that Java\'s @Override has the C# equivalent of the override keyword on methods. However, since Java 1.6 the @Override annotation can

4条回答
  •  一向
    一向 (楼主)
    2021-02-13 03:24

    There is similar functionality: explicit interface implementation.

    public interface IA { 
      void foo(); 
      // void bar(); // Removed method. 
    } 
    
    public class B : IA { 
      void IA.foo() {}
      void IA.bar() {} // does not compile
    } 
    

    The problem is that if you do this you cannot call the methods through the this pointer (from inside the class) or through an expression that evaluates to a B -- it is now necessary to cast to IA.

    You can work around that by making a public method with the same signature and forwarding the call to the explicit implementation like so:

    public class B : IA { 
      void IA.foo() { this.foo(); }
      public void foo() {}
    } 
    

    However this isn't quite ideal, and I 've never seen it done in practice.

提交回复
热议问题