C#委托的实现

王朝学院·作者佚名  2009-11-07  
宽屏版  字体: |||超大  

1 using System;

2 using System.Collections.Generic;

3 using System.Text;

4

5 namespace MyDelegate

6 {

7 class Program

8 {

9 static void ZsEat(string food)

10 {

11 Console.WriteLine("张三吃"+food);

12 }

13

14 static void Main(string[] args)

15 {

16 ZsEat("西瓜");

17 Console.ReadKey();

18 }

19 }

20 }

输出:张三吃西瓜

这个程序对任何的初学者来说都不难吧?

接下来用委托:

using System;

using System.Collections.Generic;

using System.Text;

delegate void EatDelegate(string food); //声明一个委托,需要注意的是此委托的返回值,参数类型,参数的数目需和将代理的方法(本例:ZsEat)一致。

namespace MyDelegate

{

class Program

{

static void ZsEat(string food)

{

Console.WriteLine("张三吃" + food);

}

static void Main(string[] args)

{

//ZsEat("西瓜");

EatDelegate zs = new EatDelegate(ZsEat); //将方法和委托关联起来

zs("西瓜");

Console.ReadKey();

}

}

}

注:实例化委托对象,会造成系统上资源的浪费,这样我们可以使用匿名方法。

1 using System;

2 using System.Collections.Generic;

3 using System.Text;

4

5 delegate void EatDelegate(string food); namespace MyDelegate

6 {

7 class Program

8 {

9 static void Main(string[] args)

10 {

11 EatDelegate chain = null;

12 chain += delegate(string food) { Console.WriteLine("张三吃" + food); };

13 chain("西瓜");

14 Console.ReadKey();

15 }

16 }

17 }

总结:Public delegate void SomeHandler(参数);

SomeHandler sh = new SomeHandler(这里写跟定义的委托有一样返回值,一样参数类型的方法名称);

//调用

sh(参数);

你可以用委托调用某种类型的方法

只要符合你的委托 ,它将能调用所有可访问的同类方法.

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有