日期:2014-05-16  浏览次数:20782 次

C#学习笔记(6)委托
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("还没到下班时间!"); }
        }
    }
}