我正在使用事件作为游戏模型的一部分,并且为了扩展性和代码"地点性"的缘故,我需要能够否决大多数行为.
更清楚的是,几乎每种具有副作用的方法都采用以下形式:
public event TryingToDoSomethingHandler TryingToDoSomething;
public event SomethingHappenedHandler SomethingHappened;
/*
* Returning true indicates Something happened successfully.
*/
public bool DoSomething(...)
{
//Need a way to indicate "veto" here
TryingToDoSomething(...);
//Actual do it
SomethingHappened(...);
return true;
}
Run Code Online (Sandbox Code Playgroud)
我想要的是TryingToDoSomething(...)能够指示已注册的事件处理程序对象(通过返回false,修改out参数或其他内容).所以代码在道德上等同于:
/*
* Returning true indicates Something happened successfully.
*/
public bool DoSomethingImproved(...)
{
//Pretty sure multicast delegates don't work this way, but you get the idea
if(!TryingToDoSomething(...)) return false;
//Actual do it
SomethingHappened(...);
return true;
}
Run Code Online (Sandbox Code Playgroud)
在C#/ .NET中是否有可接受的或标准的方法来执行此操作?
你在考虑Cancelable事件吗?该框架广泛使用它.
创建一个EventArgs具有Cancel实现get/set 的属性的类.然后,事件处理程序可以将Cancel属性设置为true,您可以在调用返回时进行检查.
public bool TrySomething()
{
CancelEventArgs e = new CancelEventArgs();
if (Event1 != null) Event1.Invoke(e);
if (e.Cancel == false)
{
if (Event2 != null) Event2.Invoke(e);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
409 次 |
| 最近记录: |