Equivalent of Java 1.6 @Override for interfaces in C#

后端 未结 4 964
慢半拍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.

    0 讨论(0)
  • 2021-02-13 03:41

    As stated, you cannot get that kind of control from an interface alone in C#. You could get it from an abstract class however. For the purpose of completeness, here is what you could do:

    public interface IA
    {
        void Foo();
        //void Bar(); - removed
    }
    
    public abstract class A : IA
    {
        virtual void Foo()
        { }
    
        // Removed method
        //virtual void Bar()
        //{ }
    }
    
    public class B : A
    {
        public override void Foo()
        { }
    
        //throws an error like the one you were receiving regarding no method to override.
        public override void Bar()
        { }
    }
    
    0 讨论(0)
  • 2021-02-13 03:43

    Not really, although VB.Net does.

    You could implement the method explicitly and have that call the normal public version:

    public void bar() { ... } 
    void IA.bar() { bar(); }
    
    0 讨论(0)
  • 2021-02-13 03:48

    The @Override for interface in Java means 'implements'. When in Java a class implements an interface method and that method's signature is changed or the method is removed from the interface later the java compiler starts complaining about it.

    This way it prevents the method to become 'dead code', you either have to remove the @Override annotation (so the method becomes a normal method) or remove or change the method to match the interface again. This is a very nice feature to keep your code clean. I would like C# to have this feature too.

    I use explicit implementing as much as I can.

    By the way: Resharper shows it when a method implements an interface method.

    0 讨论(0)
提交回复
热议问题