C# 中自定义事件

自定义事件的步骤:

1.声明委托:

public delegate yourActionEventHandler(Object sender,ArguEvent e);

 

2.声明事件

public event yourActionEventHandler yourAction;

 

3.注册事件:

Class class = new Class();

class.yourAction += new yourActionEventHandler(Object sender,ArguEvent e);

 

4.实现事件处理函数:

public void yourActionEventHandler(Object sender,ArguEvent e)

{

//Here is your code

}

5.触发事件

public void Button1_Click(Object sender,ArguEvent e)

{

    yourAction(this,ArguEvent.Empty);

}

 

实例代码, 在class2中声明、触发事件,在class1中注册,处理事件

class1

    {

        static void Main(string[] args)

        {

            class2 ts = new class2();

            ts.CloseAction += new    class2.CloseActionEventHandler(ts_CloseAction);





            class2 ts2 = new class2();//此处引入第二个Class2的实例 作对比之用

            ts.Run();
       //ts2.Run(); 该方法如果执行了,编译器会报Class2中的CloseAction未将对象的引用设置到对象的实例,原因就是ts2并没有注册事件。 Console.Read(); } static void ts_CloseAction(object sender, EventArgs e) { Console.WriteLine("触发了Test事件"); } } class2 { public delegate void CloseActionEventHandler(Object sender, EventArgs e); public event CloseActionEventHandler CloseAction; public void Run() { CloseAction(this, EventArgs.Empty); } }

  

你可能感兴趣的:(自定义)