Do I need to delegate a chain of delegates with a null delegate?

In the CLR via C # , Jeffrey Richter gives the following example of a delegation chain (p. 406):

internal delegate void Feedback(Int 32 value);

Feedback fb1 = new Feedback(method1);  // in the book, these methods
Feedback fb2 = new Feedback(method2);  // have different names
Feedback fb3 = new Feedback(method3); 

Feedback fbChain = null;
fbChain = (Feedback) Delegate.Combine(fbChain, fb1);
fbChain = (Feedback) Delegate.Combine(fbChain, fb2);
fbChain = (Feedback) Delegate.Combine(fbChain, fb3);

Why should the first call Delegate.Combinego to null Delegate? Here is how I would think it should be written:

Feedback fbChain = (Feedback) Delegate.Combine(fb1, fb2);
fbChain = (Feedback) Delegate.Combine(fbchain, fb3);
+3
source share
2 answers

That's right - you don't have to start from scratch. What it Delegate.Combinedoes is return a new delegate with a call list of the first argument added to the call list of the second argument. If one of the arguments is null, it just returns the other delegate that you passed.

, Combine . :

Feedback fbChain = method1;
fbChain += method2;
fbChain += method3;

fbChain = new Feedback(method1) + new Feedback(method2) + new Feedback(method3);

+ Combine. , , Delegate.Combine( , )

+7

, , :

Feedback fbChain = (Feedback) Delegate.Combine(fb1, fb2, fb3);
+2

Source: https://habr.com/ru/post/1742470/


All Articles