2013-05-09 13 views
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(); 
    } 
} 

每当收到方法是从一个派生类叫做它应该通过调用TimerReset方法复位定时器时间。我能否提供Recieve方法来重置计时器的逻辑?所以当我在派生类中重写这个成员时,我不必担心重置计时器吗?

+0

你尝试了吗?似乎尝试它(或概念)就像提问并等待回应一样快。顺便说一句,我敢肯定你可以 - 至少我30秒的测试表明你可以。 – Tim 2013-05-09 07:41:42

回答

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

微软对这些方法的命名约定似乎是为['Control.SetBoundsCore()']添加一个“Core”后缀(http://msdn.microsoft.com/zh-cn/library/system.windows .forms.control.setboundscore.aspx)。 (Control.SetBounds()的实现除了调用SetBoundsCore()外,还有其他的工作。) – 2013-05-09 08:12:51

+0

@Matthew:我现在没有那么做。感谢您的建议。我更新了我的答案。 – 2013-05-09 08:15:47

+0

谢谢,这对我很有用。 – Rene 2013-05-09 08:20:59

相关问题