Removing delegates from the network

class Program
{
    internal delegate int CallBack(int i);

    static void Main(string[] args)
    {
        CallBack callbackMethodsChain = null;
        CallBack cbM1 = new CallBack(FirstMethod);
        CallBack cbM2 = new CallBack(SecondMethod);

        callbackMethodsChain += cbM1;
        callbackMethodsChain += cbM2;

        Delegate.Remove(callbackMethodsChain, cbM1);
    /*L_0039: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Remove(class  [mscorlib]System.Delegate, class [mscorlib]System.Delegate)
        L_003e: pop 
        L_003f: ldloc.0 */

        Trace.WriteLine(callbackMethodsChain.GetInvocationList().Length);
        //Output: 2 **WTF!!!**


        callbackMethodsChain -= cbM1;
        /*
    L_0054: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Remove(class   [mscorlib]System.Delegate, class [mscorlib]System.Delegate)
          L_0059: castclass Generics.Program/CallBack
          L_005e: stloc.0 
          L_005f: ldloc.0 
        */
        Trace.WriteLine(callbackMethodsChain.GetInvocationList().Length);
        //Output: 1
    }

    private static int FirstMethod(int test)
    {            
        Trace.WriteLine("FirstMethod");
        return test;
    }

    private static int SecondMethod(int test)
    {
        Trace.WriteLine("SecondMethod");
        return test;
    }
}

So, we always need to use (CallBack) Delegate.Remove (callbackMethodsChain, cbM1); remove a delegate from the chain. This is not obvious.

+5
source share
2 answers

The delegate is immutable, which means you cannot change it. Any methods that seem to change it, such as "adding" to it or "subtracting" from it, will actually return a new delegate with the changes.

So this will not work:

a.Remove(b);

But this:

a = a.Remove(b);

in terms of calling the Remove method.

Note that the following syntax does the right thing:

a -= b;

Remove , , , , , - .

+12

  , ..    -   [CbM1, cbM2, cbM2, cbM3]

u [cbM1, cbM2,   cbM3, cbM4, cbM5, cbM1, cbM2],      [CbM1, cbM2,   cbM3, cbM4, cbM5, cbM1, cbM2] -   [cbM1, cbM2],   [cbM1, cbM2, cbM3, cbM4, cbM5]

u [cbM1, cbM2,   cbM3, cbM4, cbM5], , [cbM1, cbM2,   cbM3, cbM4, cbM5] - [cbM1, cbM5]    [cbM1, cbM2, cbM3, cbM4, cbM5]

+1

All Articles