C# in depth 阅读笔记-- 委托

委托(delegate) 

1. 相当于C语言的函数指针,执行委托,就是执行相应代理的方法.

2. 使用委托的步骤  

 a. 声明委托类型(delegate)

 委托的签名决定了委托可以代理的方法的类型,方法的签名要去委托的签名一致 

例:delegate void StringProcessor (string input); 

b. 定义要执行的方法 

以下5个方法中,只有第1个跟最后一个方法的签名与委托一致,才可以被委托调用。

void PrintString (string x)
void PrintInteger (int x)
void PrintTwoStrings (string x, string y)
int GetStringLength (string x)   //返回值不一样也不行

void PrintObject (object x)   //object是string的基类  

c. 创建委托对象 

StringProcessor proc1, proc2;
proc1 = new StringProcessor(StaticMethods.PrintString);  //指向一类方法
InstanceMethods instance = new InstanceMethods();
proc2 = new StringProcessor(instance.PrintString);   //指向一实例方法 

d. 调用执行委托对象 

 

每个委托对象都有个Invoke(参数)方法去执行委托,但是也可以把委托对象就看作是个方法,直接执行  

3. 示例 

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 Background
{
public static void Note(string note)
{
Console.writeLine ("({0})", note);
}
}
class SimpleDelegateUse
{
static void Main()
{
Person jon = new Person("Jon");
Person tom = new Person("Tom");
StringProcessor jonsVoice, tomsVoice, background;
jonsVoice = new StringProcessor(jon.Say);
tomsVoice = new StringProcessor(tom.Say);
background = new StringProcessor(Background.Note);
jonsVoice("Hello, son.");
tomsVoice.Invoke("Hello, Daddy!");
background("An airplane flies past.");
}
}

 4. 委托的合并与删除(Combining and removing delegates)

 一个委托可以代理一个方法,其实也可以代理很多的方法,通过合并操作,可以合并多个委托构成一个 代理列表(invocation list), 这样执行该委托就可以执行列表里的一序列方法。同理,可以从这个列表里删除某一委托,就是删除代理的某一方法。 

委托具有不变性,跟字符串的不变性一样,一旦创建了个委托对象就不可改变该委托,委托的合并与删除都会返回一个新的委托

 合并的方法: Delegate.Combine(x,y)   简写 + 或  +=   

 删除的方法: Delegate.Remove(source,value)  简写 - 或 -= 

 

 1using System;
 2
 3namespace Test
 4{
 5    delegate void Action();
 6    class Program
 7    {
 8        static void Main(string[] args)
 9        {
10            Action x = new Action(OutputOne);
11            Action y = new Action(OutputTwo);
12
13            //委托的合并
14            Console.WriteLine("委托的合并");
15            x += y;
16            x();
17            Console.WriteLine();
18
19            //委托的删除
20            Console.WriteLine("委托的删除");
21            x -= y;
22            x();
23
24        }

25
26        static void OutputOne()
27        {
28            Console.WriteLine("输出X");
29        }

30
31        static void OutputTwo()
32        {
33            Console.WriteLine("输出Y");
34        }

35    }

36}

37

5. 委托一般不单独使用,一般用在事件里 

 事件并不是委托的实例,是Add/Remove方法对,相当于属性的getters/settters 

posted @ 2008-07-11 13:46  笑少  阅读(568)  评论(2编辑  收藏  举报