Multicast delegation:
static void Main(string[] args) { Action dele = DoSomething; dele += DoSomething1; dele += new People().Say; dele += DoSomething2; dele += DoSomething; dele -= DoSomething; dele -= DoSomething1; dele -= new People().Say; dele -= DoSomething2; dele.Invoke(); Console.Read(); } public static void DoSomething() { Console.WriteLine($"Hello!"); } public static void DoSomething1() { Console.WriteLine($"Hello, 2!"); } public static void DoSomething2() { Console.WriteLine($"Hello, 3!"); }
You can add or remove methods,
The remove method starts from the tail and only removes one at a time. If no match is found, nothing happens
Result:
Combining the above code with the result, it is found that the instance method of People has not been removed
The methods of different instances of the same class do not match
If you need to remove People's say method above, you should declare a variable to save the instance for removal
Asynchronous execution of delegation
Action dele = DoSomething; dele += DoSomething1; dele += new People().Say; dele += people.Say; dele += DoSomething2; dele += DoSomething; dele.BeginInvoke(null, null);
The above method will report an error when the delegate is a multicast delegate;
If you want each method to execute asynchronously, you can do the following:
Action dele = DoSomething; dele += DoSomething1; dele += new People().Say; dele += people.Say; dele += DoSomething2; dele += DoSomething; //Can be as follows foreach (Action ac in dele.GetInvocationList()) { ac.BeginInvoke(null, null); }
During breakpoint monitoring, it is found that the Target of static method is null, and the Target of instance method is the instance to which it belongs
If a multicast delegate has a return value type, it returns the value of the last method execution. The previous values are lost
So in general, multi-channel delegates have no return value