How does the + operator work for combining delegates?

前端 未结 2 1561
粉色の甜心
粉色の甜心 2021-01-05 03:26

For example:

delegate void SomeDelegate();

SomeDelegate a = new SomeDelegate( () => Console.WriteLine(\"A\") );
SomeDelegate b = new SomeDelegate( () =&g         


        
2条回答
  •  无人及你
    2021-01-05 04:12

    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.

提交回复
热议问题