Force base method call

后端 未结 13 1873
独厮守ぢ
独厮守ぢ 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:42

    The following example throws an InvalidOperationException when the base functionality is not inherited when overriding a method.

    This might be useful for scenarios where the method is invoked by some internal API.

    i.e. where Foo() is not designed to be invoked directly:

    public abstract class ExampleBase {
        private bool _baseInvoked;
    
        internal protected virtual void Foo() {
            _baseInvoked = true;
            // IMPORTANT: This must always be executed!
        }
    
        internal void InvokeFoo() {
            Foo();
            if (!_baseInvoked)
                throw new InvalidOperationException("Custom classes must invoke `base.Foo()` when method is overridden.");
        }
    }
    

    Works:

    public class ExampleA : ExampleBase {
        protected override void Foo() {
            base.Foo();
        }
    }
    

    Yells:

    public class ExampleB : ExampleBase {
        protected override void Foo() {
        }
    }
    

提交回复
热议问题