今天把委托和事件研究了一个,winForm环境下,一般的小例子都是字符界面,我为了运用一下,写了winForm Common.cs:using System; using System.Collections.Generic; using System.Text; namespace DelegateAndEvent.App_Code { public class Common { //定义全局变量. public static string txt = ""; #region 定义方法 public string HelloCSharp(string name) { txt += "hello " + name;//这样做是为了看到委托可以执行多个方法. return "hello " + name; } public string HiCSharp(string name) { txt += "hi " + name; return "hi " + name; } #endregion #region 定义委托 //定义委托和定义方法类似,区别是加个delegate.去掉方法体,只写方法签名. public delegate string SayHi(string name); //委托可以像普通变量一样使用.区别在于可以把多个方法赋给委托. public SayHi dlgt1, dlgt2; //使用委托 public void useDelegate(string name, SayHi sayHi) { sayHi(name); } #endregion #region 事件 //声明事件 public event SayHi hiEvent; //触发事件 public void causeEvent() { hiEvent += HelloCSharp; hiEvent += HiCSharp; if (hiEvent != null) { hiEvent("crane"); } } #endregion } } MainFrm.cs:using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using DelegateAndEvent.App_Code; namespace DelegateAndEvent { public partial class MainFrm : Form { Common common = new Common(); public MainFrm() { InitializeComponent(); } private void btnOk_Click(object sender, EventArgs e) { //this.lblShow.Text += common.HelloCSharp("tree"); //测试委托 common.dlgt1 = common.HelloCSharp;//只写方法签名,不加() common.dlgt1 += common.HiCSharp;//虽然两个方法都调用了,但是返回值只返回最后一次调用的值. //this.lblShow.Text += common.dlgt1("tree");//使用委托就像使用方法一样. //this.lblShow.Text = Common.txt; //用委托做参数 //common.useDelegate("tree", common.dlgt1); //this.lblShow.Text = Common.txt; //事件 /*这里的问题是不能用common.hiEvent();这样引用. 原因是需要在这个类里定义一个事件变量. */ common.causeEvent(); this.lblShow.Text = Common.txt; } } }