

//内置的委派类型-----事件处理器
using System;
class UsingEventHandler
{
private void AddMethod()
{
Console.WriteLine ("asdfafsdafasfas");
}
private void DoAdd(object o,EventArgs e)
{
Console.WriteLine ("chufa:{0}",o.ToString());
AddMethod();
}
static void Main()
{
UsingEventHandler myevent=new UsingEventHandler();
calc mycalc=new calc();
mycalc.evtDocalc+=new EventHandler(myevent.DoAdd);
Console.WriteLine ("----------------");
mycalc.DoCalc();
Console.Read ();
}
}
class calc
{
public event EventHandler evtDocalc;
public void DoCalc()
{
/*指定其支持的委派为EventHandler,而触发的evtDocalc的程序代码,
必须传入两个指定类型的参数,第一个为目前的类对象,因此直接传入this关键字,
EventHandler由于不包含事件的相关信息,因此传入EventArgs类的Empty属性值*/
evtDocalc(this,EventArgs.Empty);
}
}
-------------------------------------------------------------------------
using System;
using System.Collections.Generic;
namespace DelegateEvent
{
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine ("多重传送委派");
PrintSave ps=new PrintSave();
DelegatePrintSave delegateps=null;
delegateps+=new DelegatePrintSave(ps.Print);
delegateps+=new DelegatePrintSave(ps.Save );
delegateps();
Console.WriteLine ("多重传送事件");
EventAddSub eventaddsub=new EventAddSub();
eventaddsub.px=10;
eventaddsub.py=5;
AddSub addsub=new AddSub();
//向事件中加入两个委派的方法的引用
eventaddsub.doEvent+=new delegateAddSub(addsub.Add);
eventaddsub.doEvent+=new delegateAddSub(addsub.Sub);
//引用OnEvent方法时,触发doEvent
eventaddsub.OnEvent();
Console.Read();
}
}
public delegate void DelegatePrintSave();
public class PrintSave
{
public void Print()
{
Console.WriteLine ("Finished Save! ,Starting Printing!");
Console.WriteLine ("File finished Printing!");
}
public void Save()
{
Console.WriteLine ("Finished Edit! ,Starting Saving!");
Console.WriteLine ("File finished Saving!");
}
}
public delegate void delegateAddSub(int x,int y);
public class AddSub
{
public void Add(int x,int y)
{
int bResult;
bResult=x+y;
Console.WriteLine ("{0}+{1}={2}",x,y,bResult);
}
public void Sub(int x,int y)
{
int bResult;
bResult=x-y;
Console.WriteLine ("{0}-{1}={2}",x,y,bResult);
}
}
public class EventAddSub
{
private int x;
private int y;
public int px
{
set{x=value;}
}
public int py
{
set{y=value;}
}
public event delegateAddSub doEvent;
public void OnEvent()
{
doEvent(x,y);
}
}
}