参考:.NET 中的委托
委托的两大用处
1、委托可以实现方法作为参数进行传递,如
/// <summary>
/// the English speaker.
/// </summary>
/// <param name="name">The name.</param>
public void EnglishSpeaker(string name)
{
Console.WriteLine(
string.Format("Hello my name is {0} and I am English speaker.\n", name));
} /// <summary>
/// the Chineses speaker.
/// </summary>
public void ChineseSpeaker(string name)
{
Console.WriteLine(
string.Format("您好我的名字叫{0},我是讲普通话的。\n", name));
} /// <summary>
/// The base say function.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="speaker">The speaker.</param>
private static void Say(string name, SpeakDelegate speaker)
{
///Inoke the speaker function.
speaker(name);
} ///传递函数名进行委托方法绑定
Program.Say("钧航", ChineseSpeaker);
Program.Say("JK.Rush", EnglishSpeaker);
2、委托可以进行计算,加减,使得运行委托后就按顺序运行委托所承载的方法
namespace Multi_Delegate
{
delegate void StringProcessor();
public class Person
{
private string _Name;
public Person(string name)
{
this._Name = name;
} public void Say()
{
Console.WriteLine("Hello my name is {0}, what's your name.\n", this._Name);
} public void Reply()
{
Console.WriteLine("Hello my name is {0} and nice to meet you.\n", this._Name);
}
} class Program
{
static void Main(string[] args)
{
Person Jack = new Person("Jack");
Person Oliver = new Person("Oliver");
StringProcessor sp = null;
//绑定多播方法调用
sp += Jack.Say;
sp += Oliver.Reply;
sp();
Console.ReadKey();
}
}
}
下面的代码是我模块winform的事件机制,一看就懂。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace ClassLibrary.事件
{
class 模拟控件事件机制
{ } public class Form1
{
MyButton button1;
public Form1()
{
FormIni();
button1.Text = "";
}
public void FormIni()
{
this.button1 = new MyButton("button1");///
button1.TextChanged += new MyButton.MyButtonTextChangedHandler(Button1OnTextChanged) ;
} void Button1OnTextChanged(object send, MyButtonEventArgs e)
{
Console.WriteLine("button1的Text属性改变后调用,MyButtonEventArgs的message信息为:"+e.Message);
} } /// <summary>
/// 定义Button
/// </summary>
class MyButton
{
/// <summary>
/// 按钮的Text
/// </summary>
private string text;
public string Text
{
get { return text; }
set { text = value; OnTextChanged(new MyButtonEventArgs(name)); }
}
private string name; public string Name
{
get { return name; }
set { name = value; }
}
public MyButton(string name)
{
Name = name;
} ///定义事件的委托
public delegate void MyButtonTextChangedHandler(object sender, MyButtonEventArgs e); ///定义事件
public event MyButtonTextChangedHandler TextChanged;
///定义引发事件的方法OnTextChanged()
private void OnTextChanged(MyButtonEventArgs e)
{
e.Message = name;
Console.WriteLine("MyButton的Text属性改变,MyButton控件的事件TextChanged发生了,转入信息:"+e.Message);
TextChanged(this, e);///如果没有这一行,MyButton的Text改变后引起的其它操作就不能运行
} } /// <summary>
/// 自定义事件参数
/// </summary>
class MyButtonEventArgs
{
private string message;/// public string Message
{
get { return message; }
set { message = value; }
} public MyButtonEventArgs(string message)
{
this.message = message;
} } }