Force base method call

后端 未结 13 1871
独厮守ぢ
独厮守ぢ 2020-12-11 00:15

Is there a construct in Java or C# that forces inheriting classes to call the base implementation? You can call super() or base() but is it possible to have it throw a comp

13条回答
  •  误落风尘
    2020-12-11 00:36

    EDIT Misread construct as constructor. Leaving up as CW since it fits a very limited subset of the problem.

    In C# you can force this behavior by defining a single constructor having at least one parameter in the base type. This removes the default constructor and forces derived types to explcitly call the specified base or they get a compilation error.

    class Parent {
      protected Parent(int id) {
      }
    }
    
    class Child : Parent { 
      // Does not compile
      public Child() {}
      // Also does not compile
      public Child(int id) { }
      // Compiles
      public Child() :base(42) {}
    
    }
    

提交回复
热议问题