C# 事件与委托

委托 和 事件在 .Net Framework中的应用非常广泛.这里主要介绍页面间交互的应用
举例:单击Form1的Button1  Form2的textbox值与Form1 相同
1,定义一个事件委托类
 public class EventBridge
{
    public delegate void MyDelegate(string str);
    public static evevt Mydelegate OnDrawHandle;
   
    public void OnDraw(string str)
    {
       if(EventBridge.OnDrawHandle!=null)
          EventBridge.OnDrawHandle(str);
    }
}

2 Form1订阅接收事件
构造的时候订阅
public Form1()
{
    InitializeComponent();
    EventBridge.OnDrawHandle+=new EventBridge.MyDelegate(EventBridge_OnDrawHandle);  
}

 void EventBridge_OnDrawHandle(string str)
        {
            textBox1.Text = str;
        }

3 Form2发布事件
Public event EventHandle OnDraw;
Public EventBridge eventBridge;
public Form2()
{
  InitializeComponent();
  eventBridge=new EventBridge();
  OnDraw+=new EventHandle(Form2_OnDraw);
}

void Form2_OnDraw(object sender, EventArgs e)
{
    eventBridge.OnDraw(textBox1.Text);
}

private void button1_Click(object sender, EventArgs e)
{
    Form2_OnDraw(sender, e);
}

 




一个经典的事件与委托示例:
一只猫,两只老鼠。猫叫的时候,老鼠自然逃跑……
定义一个类Cat:

    public class Cat
    {
        private string name;
        public Cat(string name)
        {
            this.name = name;
        }

        public  delegate void CatShoutEventHandle();
        public  CatShoutEventHandle CatShout;

        public void Shout()
        {
            Console.WriteLine("我是,{0}。喵!",name);
            if (CatShout != null)
            {
                CatShout();
            }
        }
    }


定义另一个类Mouse:

    public class Mouse
    {
        private string name;
        public Mouse(string name)
        {
            this.name = name;
        }

        public void Run()
        {
            Console.WriteLine("老猫来了,{0}快跑!",name);
        }
    }

 

main函数方法

    class Program
    {
        static void Main(string[] args)
        {
            Cat cat = new Cat("小白");
            Mouse mouse1 = new Mouse("Larry");
            Mouse mouse2 = new Mouse("Jack");

            cat.CatShout += new Cat.CatShoutEventHandle(mouse1.Run);//登记事件
            cat.CatShout += new Cat.CatShoutEventHandle(mouse2.Run);

            cat.Shout();

            Console.ReadKey();
        }
    }

posted @ 2009-07-08 09:33  wakerobin  阅读(428)  评论(0编辑  收藏  举报