提供了抽象的方法逻辑

本文关键字:方法 抽象的 | 更新日期: 2023-09-27 18:12:53

我有这样一个抽象类:

     public abstract class Base
{
    protected Timer timer = new Timer { AutoReset = false, Interval = 5000 };
    private bool _isTimedOut = false;
    public bool IsTimedOut { get { return _isTimedOut; } }
    public Base()
    {
        timer.Elapsed += (o, args) => _isTimedOut = true;
    }
    public abstract int Recieve(byte[] buffer);
    private void TimerReset()
    {
        timer.Stop();
        timer.Start();
    }
}

每当从派生类调用receive方法时,它应该通过调用TimerReset方法重置计时器。我可以提供接收方法的逻辑重置定时器吗?所以当我在派生类中重写这个成员时,我不必担心重置计时器?

提供了抽象的方法逻辑

您可以定义您的Receveive函数调用ResetTimer方法,然后调用另一个抽象接收函数(ReceiveCore):

public abstract class Base
{
    protected Timer timer = new Timer { AutoReset = false, Interval = 5000 };
    private bool _isTimedOut = false;
    public bool IsTimedOut { get { return _isTimedOut; } private set; }
    public Base()
    {
        timer.Elapsed += (o, args) => _isTimedOut = true;
    }
    public int Recieve(byte[] buffer) // This method cannot be overridden. It calls the TimerReset.
    {
        TimerReset();
        return RecieveCore(buffer);
    }
    protected abstract int RecieveCore(byte[] buffer); // This method MUST be overridden.
    private void TimerReset()
    {
        timer.Stop();
        timer.Start();
    }
}