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

前端 未结 4 1436
不思量自难忘°
不思量自难忘° 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 05:02

    An option would be to have the Abstract class do the calling in this manner. Otherwise, there is no way in c# to require an inherited class to implement a method in a certain way.

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

    Doing this creates the desired public facing method in the abstract class, giving the abstract class over how and in what order things are called, while still allowing the concrete class to provide needed functionality.

提交回复
热议问题