0

我有这个抽象类:

     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();
    }
}

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

4

1 回答 1

1

您可以定义您的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();
    }
}
于 2013-05-09T07:41:47.453 回答