gpt4 book ai didi

c# 在函数完成时订阅事件?

转载 作者:行者123 更新时间:2023-11-30 12:20:11 24 4
gpt4 key购买 nike

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp13
{
class Program
{
public class Subscriber
{
public static void Main()
{
Publisher publisher = new Publisher();


publisher.BeginAdd += AddCallback;
publisher.EndAdd += EndCallBack;

Console.WriteLine(publisher.Multiply(2.3f, 4.5f));


publisher.BeginAdd -= AddCallback;
publisher.EndAdd -= EndCallBack;
Console.WriteLine(publisher.Multiply(3.3f, 4.4f));

Console.ReadLine();
}
public static void AddCallback(string message)
{
Console.WriteLine("Callback - " + message);
}

public static void EndCallBack(string message)
{
Console.WriteLine("Callback - " + message);
}
}
public class Publisher
{
public delegate void Notify(string message); // Declare delegate.
public event Notify BeginAdd; // Declare event.
public event Notify EndAdd;

public float Multiply(float a, float b)
{
OnBeginAdd(); // Raise event.
OnEndAdd();
return a * b;
}
private void OnBeginAdd()
{
if (BeginAdd != null)
BeginAdd("Starting multiplication!"); // Call callback method.
}

private void OnEndAdd()
{
if (EndAdd != null)
EndAdd("Completing multiplication!");
}
}
}
}

如何更正添加 OnEndAdd() 的语法;进入乘法函数,以便它只在函数完成后回调?我试过在 return 语句之后添加它,但这显然不起作用,似乎无法找到另一种方法......

最佳答案

一旦 Multiply 函数返回,控件就会离开发布者,因此这里需要进行一些设计更改。

你的意思是on completion of the multiply operation (不一定是整个函数调用),以下更改就足够了。

        public float Multiply(float a, float b)
{
OnBeginAdd();
var result = a * b;
OnEndAdd();
}

更漂亮的 (tm) 方法可能是创建另一个类,例如OperationScope类型 IDisposable为您调用 OnBeginAdd/OnEndAdd - 例如:

        public float Multiply(float a, float b)
{
using (new OperationScope(this)) //This is IDisposable and calls OnBeginAdd & OnEndAdd
{
return a * b;
}
}

注意:除了使用 IDisposable 类之外,还有其他类似的方法,例如传递 Func<xyz>将实际工作(乘以)到另一个调用 OnBeginAdd 的方法/OnEndAdd .

关于c# 在函数完成时订阅事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53166995/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com