代理就是让代理类去执行别的类的代码,C++设计模式中也有相似的方法,不过那个是用指针实现,而C#的明显要简洁。
关键的点:接口参数和返回值类型要一样
下面是别处的一个例子
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace testDelegate
{
delegate int MyDelegate(int i);
class Program
{
public int F1(int i) //声明一个实例方法F1(int i)
{
Console.WriteLine("调用实例方法F1(int i)");
return i;
}
public static int F2(int j) //声明一个静态方法F2(int j)
{
Console.WriteLine("调用静态方法F2(int j)");
return j;
}
static void Main(string[] args)
{
Program p = new Program();
MyDelegate d1 = new MyDelegate(p.F1); //创建d1实例
int i = d1(10);
Console.WriteLine("i的值为:"+i);
MyDelegate d2 = new MyDelegate(Program.F2); //创建d2实例
int j = d2(20);
Console.WriteLine("j的值为:" + j);
//还可以这么玩
MyDelegate d3 = d1 + d2;
//d4实例依次调用Program类的F1、F2、F2、F1方法
MyDelegate d4 = d3 + d2 + d1;
//d5实例依次调用Program类的F1、F2、F1方法
MyDelegate d5 = d4 - d2;// 注意减的话是从后往前搜素
d4(30);
Console.WriteLine("hello world");
d5(20);
Console.ReadLine();
}
}
}
c#的delegate示例代码
最新推荐文章于 2024-07-25 00:09:37 发布