Don't think you are, know you are

博客园 首页 新随笔 管理

 

我们知道事件必须带两个参数的,一个是object ,传递的一般是事件的发起者,即在镶嵌有时间占位符的类内部传递 this。

另一个是一个 EventArgs 参数,我们可以定义自己的事件参数继承自 EventArgs 类,传递一些值从事件的发起者到事件的实现者。

 

例子如下,比如自己设计一个Button类

 public class MyButton
    {
        public string caption="haha";
        private string color = "red";
        public event EventHandler OnClick;
        public void Doclick()
        {
           OnClick(this,new MyArgs(this.color) );
        }
    }

 

设计自己的参数类MyArgs

 

  public class MyArgs : EventArgs
    {

        public string Color { get; set; }
        public MyArgs(string color):base()
        {
            this.Color = color;
        }   
    }

 

事件的注册与 实现者

 

 static void Main(string[] args)
        {
            MyButton btn = new MyButton();
            btn.OnClick += new EventHandler(btn_OnClick);
         // btn.OnClick += Program.btn_OnClick;   also work
            btn.Doclick();
        }

        static void btn_OnClick(object o, EventArgs  e)
        {
            MyButton b = o as MyButton;
            MyArgs ar = e as MyArgs;         
            Console.WriteLine(b.caption);
            Console.WriteLine(ar.Color);
            Console.ReadKey();
        }

 

上面两个转换能成功是因为面向对象中的,子类能替代父类句柄。

posted on 2010-07-09 23:56  炭炭  阅读(595)  评论(2编辑  收藏  举报