什么是委托实例和方法指针之间的区别? [英] What is the difference between a delegate instance and a method pointer?

查看:269
本文介绍了什么是委托实例和方法指针之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为,一个委托实例是一个函数实例互换

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

看看下面的代码:

delegate int AddDelegate(int a, int b);

AddDelegate DelegateInstance;

public void DoStuff()
{
    //I can call this without a delegate "instance":
    MethodThatTakesAdd(Add);

    //I can also call it WITH a delegate "instance"
    DelegateInstance = Add;
    MethodThatTakesAdd(DelegateInstance);
}

public int Add(int a, int b)
{
    return a + b;
}

public void MethodThatTakesAdd(AddDelegate addFunction)
{
    Console.WriteLine(addFunction(1, 2).ToString());
}



调用它似乎相当于的两种方法,如果你正在使用只有C#中,你永远不会看到其中的差别(至少我还没有到这一点)。但是,我是在呼唤回到​​这个托管代码,他们的待遇不同近来非托管代码。例如,在一个场景中,我得到错误的回调作了关于垃圾回收的委托,如果我直接使用功能,作为回调(尽管我的对象实例是围绕保持)。使用委托实例解决了这个问题。

Both ways of calling it APPEAR to be equivalent, and if you're using only C#, you'll never see the difference (at least I have not up to this point). However, I was recently unmanaged code that was calling back into this managed code, they are treated differently. For example, in one scenario, I to get the error "A callback was made on a garbage collected delegate" if I use the function directly as a callback (even though my object instance is kept around). Using the "delegate instance" fixes the problem.

有没有人在那里,知道有什么区别?

Is there someone out there that knows what the difference is?

推荐答案

术语Corretion:不是方法指针的,更合适的词是方法组。

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

在功能方面的两个语句是等价的。这就是它们产生的几乎同IL。所不同的是该委托值被存储在哪里。

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.

在第一种情况下你传递方法组添加到MethodThatTakesAdd直接。这会导致创建一个临时委托值,然后传递给MethodThatTakesAdd。这代表价值受垃圾收集MethodThatTakesAdd返回,因为它不保存价值的时刻。

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.

在第二种情况下您所分配的代表到现场的外实例。这将一般的增加委托的使用寿命,从而减少它是你的PInvoke通话过程中垃圾回收的机会。

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.

这篇关于什么是委托实例和方法指针之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆