How does the + operator work for combining delegat

2019-04-07 07:05发布

For example:

delegate void SomeDelegate();

SomeDelegate a = new SomeDelegate( () => Console.WriteLine("A") );
SomeDelegate b = new SomeDelegate( () => Console.WriteLine("B") );

SomeDelegate c = a + b;

In the last line, what does a + b translate to? I'm just curious how I would add them without using the + operator.

标签: c# delegates
2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-04-07 07:08

http://msdn.microsoft.com/en-us/library/ms173172(v=VS.80).aspx - Search for addition:

A delegate can call more than one method when invoked. This is referred to as multicasting. To add an extra method to the delegate's list of methods—the invocation list—simply requires adding two delegates using the addition or addition assignment operators ('+' or '+='). For example:

MethodClass obj = new MethodClass(); 
Del d1 = obj.Method1; 
Del d2 = obj.Method2; 
Del d3 = DelegateMethod;

//Both types of assignment are valid. 
Del allMethodsDelegate = d1 + d2; 
allMethodsDelegate += d3;

At this point allMethodsDelegate contains three methods in its invocation list—Method1, Method2, and DelegateMethod. The original three delegates, d1, d2, and d3, remain unchanged. When allMethodsDelegate is invoked, all three methods are called in order. If the delegate uses reference parameters, the reference is passed sequentially to each of the three methods in turn, and any changes by one method are visible to the next method. When any of the methods throws an exception that is not caught within the method, that exception is passed to the caller of the delegate and no subsequent methods in the invocation list are called.

Update

Both delegates derive from System.Delegate You can use the combine() methods to add two delegates together.

查看更多
Anthone
3楼-- · 2019-04-07 07:18

It is done using Delegate.Combine static method.

SomeDelegate c = Delegate.Combine(a, b) as SomeDelegate;

When using += operator it is just the same actually.

// This is the same...
eventSource.onEvent += OnEvent;

// ...as this.
eventSource.onEvent = Delegate.Combine(
    eventSource.onEvent,
    Delegate.CreateDelegate(typeof(EventSource.OnEvent), this, "OnEvent")
    ) as EventSource.OnEvent;

MulticastDelegate class (the class behind delegate keyword) do have a list of invocations, but this list is immutable. Each time you combine delegates with the += operator, a new MulticastDelegate instance get created combining the invocation list of the former two Delegate objects.

查看更多
登录 后发表回答