使用時機: 確保一個類別只會有一個實體物件, 資源共享管理…
建立一個tictoc類別
1: public sealed class tictoc
2: {
3: private DateTime startTime;
4: private static tictoc manager; // Singleton物件: tictoc類別的唯一物件
5: // 靜態建構子
6: static tictoc()
7: {
8:
9: }
10: // 預設建構子
11: private tictoc()
12: {
13: startTime = DateTime.Now;
14: }
15: // 靜態方法
16: public static tictoc Instance
17: {
18: get
19: {
20: if (manager == null)
21: {
22: manager = new tictoc();// 呼叫預設建構子並初始化startTime
23: }
24: return manager;
25: }
26: }
定義公開函式tic, toc
1: /// <summary>
2: /// 計時開始
3: /// </summary>
4: public void tic()
5: {
6: startTime = DateTime.Now;
7: }
8: /// <summary>
9: /// 計時結束
10: /// </summary>
11: /// <param name="days">日</param>
12: /// <param name="hours">時</param>
13: /// <param name="mins">分</param>
14: /// <param name="secs">秒</param>
15: /// <param name="msecs">毫秒</param>
16: public void toc(out int days, out int hours, out int mins, out int secs, out int msecs)
17: {
18: TimeSpan tspan = DateTime.Now - startTime;
19: days = tspan.Days;
20: hours = tspan.Hours;
21: mins = tspan.Minutes;
22: secs = tspan.Seconds;
23: msecs = tspan.Milliseconds;
24: }
測試tictoc類別
新增一個windows form專案
加入一個statusStrip和timer
timer tick 事件
1: int days = 0, hours = 0, mins = 0, secs = 0, msecs = 0;
2: tictoc.Instance.toc(out days, out hours, out mins, out secs, out msecs);
3: tssLabel_Time.Text =//顯示程式啟動時間
4: string.Format(
5: "系統已經執行: {0}天{1}小時{2}分{3}秒{4}毫秒", days, hours, mins, secs, msecs);
時間經過是以目前時間和建構子取得的時間
1: // 預設建構子
2: private tictoc()
3: {
4: startTime = DateTime.Now;
5: }
按下<計時開始>按鈕:
1: private void button1_Click(object sender, EventArgs e)
2: {
3: timer1.Enabled = true;
4: tictoc.Instance.tic();
5: }
重置起始時間
1: public void tic()
2: {
3: startTime = DateTime.Now;
4: }
停止計時
1: private void button2_Click(object sender, EventArgs e)
2: {
3: timer1.Enabled = false;
4: }
全站熱搜
留言列表