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

ste*_*y30 5 c# events

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!");
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Pla*_*oZA 2

一旦 Multiply 函数返回,控制权就会从发布者手中移开,因此这里需要进行一些设计更改。

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

        public float Multiply(float a, float b)
        {
            OnBeginAdd(); 
            var result = a * b;
            OnEndAdd();
        }
Run Code Online (Sandbox Code Playgroud)

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

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

注意:可能还有其他类似的方法来代替使用 IDisposable 类,例如将Func<xyz>执行实际工作(乘法)的 a 传递给另一个调用OnBeginAdd/的方法OnEndAdd