What is the difference between a delegate instance and a method pointer?

前端 未结 3 901
执念已碎
执念已碎 2021-02-08 20:29

I thought that a delegate instance was interchangeable with a function instance.

Take the following code:

delegate int AddDelegate(int a, int b);

AddDel         


        
3条回答
  •  野性不改
    2021-02-08 21:07

    Delegates are classes that are callable, and have similar behavior to function pointers. The delegate internally stores the address of the function to call (i.e. the function pointer), but also provides other functionality such as multi-casting and storing an invocation list; you can essentially invoke many functions of the same signature with one delegate instance as follows.

    public void DoStuff()
    {
        DelegateInstance += Add;
        DelegateInstance += AnotherAdd;
        DelegateInstance += YetAnotherAdd;
    
        // Invoke Add(100, 200), AnotherAdd(100, 200), and YetAnotherAdd(100, 200)
        DelegateInstance(100, 200);
    }
    

    Regarding your note about the equivalence of MethodThatTakesAdd(Add) and MethodThatTakesAdd(DelegateInstance), if you look at the MSIL that the C# compiler generates for the line MethodThatTakesAdd(Add), you will notice that the compiler is creating a delegate and wrapping the Add() method for you.

提交回复
热议问题