C# 的Delegate操作解析
如果你有学过C,C#的delegate其实很类似C的function pointer。
delegate让我们可以把function透过参数的形式来传递,也就是说delegate可以让我们把function当作first class opject来操作。下列是一个delegate的简单范例:
- using System;
- delegate void StringProcessor(string input);
- class Person
- {
- string name;
- public Person(string name) { this.name = name; }
- public void Say(string message)
- {
- Console.WriteLine("{0} says: {1}", name, message);
- }
- }
- class SimpleDelegateUse
- {
- static void Main()
- {
- Person jon = new Person("Jon");
- Person tom = new Person("Tom");
- StringProcessor jonsVoice, tomsVoice;
- jonsVoice = new StringProcessor(jon.Say);
- tomsVoice = new StringProcessor(tom.Say);
- jonsVoice("Hello, son.");
- tomsVoice.Invoke("Hello, Daddy!");
- }
- }
此范例中我们建立了声明了两个delegate的instance,分别是jonsVoice以及tomsVoice。最后用两种不同的方式调用function
使用delegate要有以下三个步骤:
1. 声明delegate type
delegate void StringProcessor(string input);
这行就是我们声明delegate type的地方,这个delegate的type是含有一个string参数且回传值为void的function。此delegate type只能接受回传值以及参数个数一模一样的function。不过有一种特殊情况:
void Test(object x);
此function也可以被assigned给此delegate的instance,因为string是继承自object
2. 建立delegate instance
StringProcessor jonsVoice, tomsVoice;
jonsVoice = new StringProcessor(jon.Say);
用new可以建立刚才宣告好得delegate instance,建立传入的参数是之后要透过delegate唿叫的function
3. 调用delegate instance的function

编译之后会把jonsVoice("Hello, son.")转成jonsVoice.Invoke("Hello, son.")
最后又会通过过delegate调用原assigned的function jon.Say("Hello, son.")
delegate很常用在UI Button的click,我们会事先宣告EventHandler的delegate instance。当button被按下时,执行对应的处理function。有点类似call back function。
每个delegate instance内部都有一个invocation list用来纪录function,也就是说一个delegate instance可以纪录不只一个function。当有多个function时,delegate会一一调用invocation list中所储存的function。我们可以通过+=以及-=运算符来新增移除function。
以下是个简单的范例:
- void HowAreYou(string sender) {
- Console.WriteLine("How are you, " + sender + '?');
- }
- void HowAreYouToday(string sender) {
- Console.WriteLine("How are you today, " + sender + '?');
- }
- Notifier greetMe;
- greetMe = new Notifier(HowAreYou);
- greetMe += new Notifier(HowAreYouToday);
- greetMe("Leonardo"); // "How are you, Leonardo?"
- // "How are you today, Leonardo?"
- greetMe -= new Notifier(HowAreYou);
- greetMe("Pereira"); // "How are you today, Pereira?"
- 评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
-
