我正在尝试编写一个抽象类,其中包含应用程序的多个组件共有的数据,并为这些组件提供通知其他组件他们正在处理的数据已更改的能力。不幸的是,没有其他组件正在接收被触发的事件。我决定写一个快速测试,看看我是否可以找出错误,但我遇到了完全相同的问题。我误解了事件的运作方式吗?或者我错过了一些明显的东西?
void Main()
{
EventHandler<string> EVENT = delegate {};
var test = new DerivedClass("test", ref EVENT, 6);
var test2 = new DerivedClass("test2", ref EVENT, 8);
test.Number = 7;
test2.Number = 4;
}
public class DerivedClass : BaseClass
{
protected override void OnChanged(object sender, string e)
{
Console.WriteLine(string.Format("Derived class event fired from {0}! New value is {1}", sender, e));
}
public DerivedClass(string name, ref EventHandler<string> handler, int val) : base(ref handler, val)
{
this._name = _name;
}
public override string ToString()
{
return _name;
}
string _name;
}
public abstract class BaseClass
{
public virtual int Number
{
get { return _number; }
set
{
_handler(this, value);
_number = value;
}
}
protected virtual void OnChanged(object sender, string e)
{
Console.WriteLine("Base class event fired! " + e);
}
protected BaseClass(ref EventHandler<string> handler, int val)
{
_number = val;
_handler = handler;
if (_handler != null) _handler += this.OnChanged;
}
protected event EventHandler<string> _handler;
protected int _number;
public override string ToString()
{
return "A BaseClass";
}
}
输出:
Derived class event fired from test! New value is 7
Derived class event fired from test2! New value is 4
答案 0 :(得分:0)
我误解了事件的运作方式吗?
可能。具体来说,您似乎认为事件是基于每个类处理的,或者子类实例将共享相同的父类实例。
您已宣布自己的活动为非static
:
protected event EventHandler<string> _handler;
因此,扩展此类的任何类的每个实例都将拥有自己的此事件实例。根据您要完成的任务,您可以考虑将事件设为静态?