1、实名委托
//定义委托
private delegate string ChangeEventHandle(); private delegate int intEventHandle(int ID); private void button1_Click(object sender, EventArgs e) {
//new一个委托 ChangeEventHandle c = new ChangeEventHandle(Function); this.Text = c.Invoke(); //委托调用 this.Text = c(); } private void button2_Click(object sender, EventArgs e) { intEventHandle c1 = new intEventHandle(Function); this.Text = c1(5).ToString(); } private string Function() { return "delegate"; } private int Function(int ID) { return ID*ID; }
2、匿名委托,不定义名称
List<int> lst = new List<int>(){0,2,3,8,9};
List<int> find = lst.FindAll(delegate(int i) { return i > 5; });
结果8,9
private void test() { label1.Invoke(new EventHandler(delegate(object o, EventArgs e) { label1.Text = "ceshi"; })); this.button1.Invoke(new MethodInvoker(delegate() { label1.Text = "ceshi"; })); }
匿名方法
delegate string MyDelagate(string val);
//中括号部分定义来了一个方法,没有名称,编译器会定指定一个名称,my为委托的名称 MyDelagate my = delegate(string param) { string str2 = " 匿名方法内部 "; return param + str1 + str2; };
实名方法
delegate string MyDelagate(string val); private void button2_Click(object sender, EventArgs e) { MyDelagate my = new MyDelagate(fun); my("实名方法"); } static void MyFun(string str) { Console.Write(str); }