c#为什么委托\事件在传递给另一个类后没有得到更新

时间:2017-01-16 13:57:02

标签: c# events reference delegates invoke

我在调用将事件传递给特定类后添加的委托时遇到问题,我认为委托将更新作为对象进行..

例如,这是我将代理传递给的类:

更新了代码(由于评论中的一些问题)

这实际上是+ - 我需要如何运行它,“ExecutorOnCalculationCompleted”永远不会调用(请忽略睡眠和同步,我将代码缩小到所需的部分)

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

1 个答案:

答案 0 :(得分:2)

您正在构造函数中直接传递委托。我想你想把这个活动放到课堂上。例如:

Plus

你现在可以这样使用它:

Multiply

如评论中所述,如果代表类型用于程序的不同部分,则可能只需要事件本身。

问题更新后

如果您想在执行程序中使用该事件,我只需将操作传递给您的每个类,如class Executor { public delegate void CalculationCompletEventHandler(int score); public event CalculationCompletEventHandler CalculationCompleted; public void Start() { CalculationCompleted += OnCalculationCompleted; Plus plus = new Plus(1, 2, FireEvent); } private void FireEvent(int score) { if (CalculationCompleted != null) { CalculationCompleted(score); } } private void OnCalculationCompleted(int score) { Console.WriteLine("OnCalculationCompleted , score=" + score); } } class Plus { private int a; private int b; private Action<int> completionAction public Plus(int a, int b, Action<int> completionAction) { this.a = a; this.b = b; this.completionAction = completionAction; } public void Calculate() { this.completionAction(a + b); } } ,{{1}},...并从执行程序调用该事件:

{{1}}