本文主要是介绍C#事件演示程序2)——写事件的三点注意,以及常用的事件处理模型,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
今天又思考了一下C#的事件处理。
如果在一个类A中定义一个事件,在类B中触发事件,然后让订阅了类A的事件的类C执行对应的方法,该怎么办?
我试了一下,竟然不能执行:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication3
... {
class programm3
...{
static void Main(string[] args)
...{
MyEvent myEvent = new MyEvent();
aaa aaa = new aaa();
myEvent.OnHehe();
}
}
public class aaa
...{
public aaa()
...{
MyEvent myEvent = new MyEvent(); //注册给了另一个对象,所以不会被执行
myEvent.hehe += new EventHandler(DisplayString);
}
public void DisplayString(object sender,EventArgs e)
...{
Console.WriteLine("hello everyone!");
}
}
public class MyEvent
...{
public event EventHandler hehe;
public void OnHehe()
...{
RaiseEvent();
}
private void RaiseEvent()
...{
if (hehe != null)
...{
hehe(this, new EventArgs());
}
}
}
}
郁闷了半天,才终于弄清楚。原来原来我对C#的事件处理机制也仅仅是一知半解,不甚清楚。
首先,定义事件的类,其定义的事件激活函数一般应该是非静态的(能否静态再研究),这就要求在外部触发事件,肯定首先要拿到该对象的实例。然后,对事件的注册是注册某个对象的事件,还有,就是包含处理动作的类一定要被加载,不然会找不到该类的。以上三点是写C#的事件非常容易倏忽的地方。但以上例子都注意了,怎么还是不行呢?原因很简单,注册针对的对象和被触发事件的对象不是一个对象!
所以,如果要实现目的,一般应该这样写:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication3
... {
class Program
...{
static void Main(string[] args)
...{
MyEvent myEvent = MyEvent.Instance;
Test test = new Test();
myEvent.OnHaha();
}
}
public class Test
...{
public Test()
...{
MyEvent.Instance.Haha += new EventHandler(DisplayString);
}
public void DisplayString(object sender, EventArgs e)
...{
Console.WriteLine("hello !");
}
}
public class MyEvent
...{
//使用单例,保证外面的引用是同一个对象
private static MyEvent _instance = new MyEvent();
public static MyEvent Instance
...{
get ...{ return _instance; }
}
public event EventHandler Haha;
public void OnHaha()
...{
RaiseHaha();
}
private void RaiseHaha()
...{
if( Haha!=null )
...{
Haha(this, new EventArgs());
}
}
}
}
这篇关于C#事件演示程序2)——写事件的三点注意,以及常用的事件处理模型的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!