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

前端 未结 3 902
执念已碎
执念已碎 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

    Terminology Corretion: Instead of method pointer, the more appropriate term is method group.

    In terms of functionality the two statements are equivalent. That is that they produce almost the same IL. The difference is where the delegate value is stored.

    In the first case you pass the method group Add to MethodThatTakesAdd directly. This causes a temporary delegate value to be created and then passed to MethodThatTakesAdd. This delegate value is subject to garbage collection the moment the MethodThatTakesAdd returns since it does not store the value.

    In the second case you assigned the delegate to a field on the outer instance. This will typically increase the lifetime of the delegate and hence reduce the chance it's garbage collected during your pinvoke call.

提交回复
热议问题