我有这个抽象类:
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方法提供重置计时器的逻辑?因此,当我在派生类中重写此成员时,我不必担心重置计时器?
答案 0 :(得分: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();
}
}