[英]C# Updating a Elapsed Time Variable to Hold Value
我正在做一個秒表任務,我們必須做自己的秒表課程。 即我不能使用秒表。 我有一個計時器,用於更新標簽,每秒更新一次。 我應該對我的班級做些什么,以便在我停下來再重新開始時保持經過的時間? 目前,它只是回到00:00:00。 請記住,這是一項任務,這就是為什么它不是執行此操作的最合邏輯的原因。
public class Time
{
//fields
DateTime startTime, stopTime, currentTime;
bool isActive = false;
bool hasStarted = false;
public string ElapsedTime
{
get
{
// TODO: return something if never started..
if (isActive == false && hasStarted == false)
{
//Exception ex = new Exception("Please start the timer."); // This should be in the StartClock method.
//return ex.ToString();
return "00:00:00";
}
// TODO: return something if running...
else if (isActive == true && hasStarted == true)
{
return DateTime.Now.Subtract(startTime).ToString(@"hh\:mm\:ss");
}
// return if started then stopped (I did this one for you)
else
{
return (stopTime - startTime).ToString(@"hh\:mm\:ss");
}
}
}
public void StartClock() // Good! The "else" is where you should be throwing the exceptions
{
//TO DO: set the startTime
if(!isActive)
{
isActive = true;
hasStarted = true;
startTime = DateTime.Now;
}
else
{
Exception ex = new Exception("Please start the timer."); // This should be in the StartClock method.
}
}
public void StopClock()
{
//sets stop time
if(isActive && hasStarted)
{
isActive = false;
stopTime = DateTime.Now;//something else
}
}
}
您可以嘗試跟蹤經過的總時間,以下一些偽代碼可能會有所幫助:
this.elapseTime = 00:00:00;
startClicked:this.startedTime = Now()
stopClicked:this.elapsedTime + = Now()-this.startedTime
getCurrentElapsedTime:返回this.elapsedTime + Now()-this.startedTime
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.