C#中委托的+=和-=深入研究

2019-12-26 11:25:40于海丽

        }
        static int Add(int a, int b)
        {
            return a + b;
        }
        static int Multiply(int a, int b)
        {
            return a * b;
        }
    }
}

 

你可以猜猜运行结果,如下图:
C#中委托的+=和-=深入研究

可以看到没有返回值的都输出了,有返回值的只输出了Mutiply的结果,那么+=内部做了哪些事?可以看一下反编译的代码:

 

复制代码
using System;
namespace Wolfy.DelegateDemo
{
    internal class Program
    {
        private static ShowMsg showMsg;
        private static MathOperation mathOperation;
        private static void Main(string[] args)
        {
            Program.showMsg = (ShowMsg)Delegate.Combine(Program.showMsg, new ShowMsg(Program.ShowHello));
            Program.showMsg = (ShowMsg)Delegate.Combine(Program.showMsg, new ShowMsg(Program.ShowHello1));
            Program.showMsg("大家新年好啊");
            Program.mathOperation = (MathOperation)Delegate.Combine(Program.mathOperation, new MathOperation(Program.Add));
            Program.mathOperation = (MathOperation)Delegate.Combine(Program.mathOperation, new MathOperation(Program.Multiply));
            Console.WriteLine(Program.mathOperation(1, 2).ToString());
            Console.Read();
        }
        private static void ShowHello(string msg)
        {