首页 > 学院 > 开发设计 > 正文

C#委托的实现

2019-11-17 04:06:37
字体:
来源:转载
供稿:网友
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(参数);

你可以用委托调用某种类型的方法
只要符合你的委托 ,它将能调用所有可访问的同类方法. 
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表