using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace demo6 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } delegate string StartWorkDelegate(); //定義委托StartWorkDelegate delegate void OffWorkDelegate(string s); //定義委托OffWorkDelegate private void button1_Click(object sender, EventArgs e) //單擊上班按鈕執行的動作 { StartOffWork sw = new StartOffWork(); //實例化StartOffWork類 /*實例化委托StartWorkDelegate*/ StartWorkDelegate SWork = new StartWorkDelegate(sw.StartWork);// // StartWorkDelegate SWork = sw.StartWork; //也可以使用這條語句實例化 label2.Text = SWork(); //調用委托,結果顯示在窗體上 } private void button2_Click(object sender, EventArgs e) { /*實例化委托OffWorkDelegate*/ //OffWorkDelegate OWork = new OffWorkDelegate(StartOffWork.OffWork); OffWorkDelegate OWork = StartOffWork.OffWork; //關聯到靜態方法 OWork("19:30"); //調用委托,參數為下班時間 } private void timer1_Tick_1(object sender, EventArgs e) //timer1的Tick事件代碼 { label1.Text = "現在時間:" + DateTime.Now.ToString(); } } public class StartOffWork //定義管理上下班類StartOffWork { public string StartWork() //實例方法 { if (DateTime.Now <= Convert.ToDateTime("20:30")) //判斷是否已經上班 { return "挺早的!"; } //返回字符串“挺早的!” else { return "你遲到了,下次可要來早點哦!"; } } public static void OffWork(string offworktime) //靜態方法 { if (DateTime.Now > Convert.ToDateTime(offworktime)) //判斷是否到了下班時間 { MessageBox.Show("辛苦了!"); } //彈出消息框 else { MessageBox.Show("還沒到下班時間!"); } } } }