How to enforce a method call (in the base class) when overriding method is invoked?

前端 未结 4 1309
不思量自难忘°
不思量自难忘° 2021-01-18 04:10

I have this situation that when AbstractMethod method is invoked from ImplementClass I want to enforce that MustBeCalled m

4条回答
  •  旧巷少年郎
    2021-01-18 04:57

    How about

    public abstract class AbstractClass
    {
        public void AbstractMethod()
        {
            MustBeCalled();
            InternalAbstractMethod();
        }
    
        protected abstract void InternalAbstractMethod();
    
        public void MustBeCalled()
        {
            //this must be called when AbstractMethod is invoked
        }
    }
    
    public class ImplementClass : AbstractClass
    {
        protected override void InternalAbstractMethod()
        {
            //when called, base.MustBeCalled() must be called.
            //how can i enforce this?
        }
    }
    

提交回复
热议问题