日期:2014-05-17 浏览次数:21043 次
using System;
// 创建一个delegate
delegate int MyHandler(int d1, int d2); 
class Test
{		
	public static int Add(int x, int y)
	{
		Console.WriteLine("Add has been invoked..");
		return x+y;
	}
	
	public int Minus(int x, int y)
	{
		Console.WriteLine("Minus has been invoked..");
		return x-y;
	}
	
	public static void Main()
	{
		Console.WriteLine("mh1:=====================================");
		MyHandler mh1 = new MyHandler(Test.Add);	//绑定静态方法;	
		Console.WriteLine("Outcome1: "+ mh1(100, 200));//==>mh1.Invoke(100, 200); ==> {jump Test.Add;}
		Console.WriteLine();
		
		Console.WriteLine("mh2:=====================================");
		Test t = new Test();
		MyHandler mh2 = new MyHandler(t.Minus);//绑定动态方法,这里其实传了两个参数:t和&Minus;
		Console.WriteLine("Outcome2: "+ mh2(100, 50));
		Console.WriteLine();
		
		Console.WriteLine("mh3:=====================================");
		MyHandler mh3 = mh1 + mh2;//   ;构建委托链;有序的;
		Console.WriteLine("Outcome3: "+ mh3(200, 100));//依次执行mh1,mh2;返回值是最后一个委托方法的返回值,在此为mh2的返回值;
		Console.WriteLine();
		
		Console.WriteLine("mh4:=====================================");
		MyHandler mh4 = mh1 + mh2 + mh3;
		Delegate[] mhs = mh4.GetInvocationList();  //使用Delegate的GetInvocationList()方法可以数组的形式获得委托链中的每一个委托,从而实现对于委托链的随机访问;
		Console.WriteLine(mhs);
		for(int i = 0; i<mhs.Length; i++) //遍历委托链;
		{
			MyHandler tempHandler =(MyHandler)mhs[i];
			Console.WriteLine("outcome4: " + i + " " + tempHandler(200, 100));
		}
		Console.WriteLine();
		
		Console.WriteLine("mh5:=====================================");
		MyHandler mh5 = delegate(int x, int y){  //绑定匿名方法;
				Console.WriteLine("匿名方法:");
				return x*y;
		};		
		Console.WriteLine("Outcome5: " + mh5(100,200));			
	}	
}


class MyHandler : MulticastDelegate
{
	//构造器;
	public MyHandler(Object object, IntPtr method);
	
	//这个方法和源代码指定的原型一样;
	public virtual void Invoke(int d1, int d2);
	
	//以下方法实现了对回调方法的异步回调,具体还没有研究过。。。
	public virtual IAsyncResult BeginInvoke(...);
	public irtual void EndInvoke(...);
} 
//MulticastDelegate内最主要的是包含了三个静态字段:
class MulticastDelegate
{
	private Object _target; //这个字段用来指出要传给实例方法的隐式参数this的值;
													//当委托对象包装的是一个静态方法时,这个字段为null;
													//当委托对象包装一个实例方法时,这个字段引用的是回调函数要操作的对象;
	private IntPtr _method;	//一个内部的整数值,CLR用它标示要回调的方法;可以理解为一个函数指针;
	private Object _invocationList;	//用来指向委托链中的下一个委托对象;
	//...
}
Console.WriteLine("mh2:=====================================");
		Test t = new Test();
		MyHandler mh2 = new MyHandler(t.Minus);//绑定动态方法,这里其实传了两个参数:t和&Minus;
		Console.WriteLine("Outcome2: "+ mh2(100, 50));
		Console.WriteLine();

mh2.Invoke(100,50)