在课堂上创建一个事件怎么样Manager
,比如一个RequestChangeSpecialData
事件。Manager
触发事件,并且将SomeClass
更改SpecialData
实例。
public class SomeClass
{
private Manager _m;
public Manager M
{
get { return _m}
set
{
// register/unregister event on property assignment
if(_m != null)
_m.RequestChangeSpecialData -= RequestChangeSpecialData;
_m = value;
if(_m != null)
_m.RequestChangeSpecialData += RequestChangeSpecialData;
}
}
public SpecialData Data { get; private set; }
private void RequestChangeSpecialData(object sender, ChangeSpecialDataEventArgs e)
{
// set the new reference
Data = e.SpecialData;
}
}
public class Manager
{
public void DoSomething()
{
// the manager class wants to do something, and wants to change the SpecialData instance.., so it fires the event RequestChangeSpecialData
SpecialData data = new SpecialData();
// if the event is bound.
if(RequestChangeSpecialData != null)
RequestChangeSpecialData(this, new ChangeSpecialDataEventArgs(data));
}
public event EventHandler<ChangeSpecialDataEventArgs> RequestChangeSpecialData;
}
public class ChangeSpecialDataEventArgs : EventArgs
{
public SpecialData Data {get; private set; }
public ChangeSpecialDataEventArgs(SpecialData Data)
{
Data = data;
}
}
未经测试(写在记事本中)
现在Manager
可以更改SpecialData
属性。这样,管理器不依赖于SomeClass
/interface 或程序集。