指向 C# 委托中方法的指针
在下面的代码中,ptrcall
是否
- 通过
obj.callMe
和obj1.callMe
方法指向堆上的 2 个位置?或者... 到 1 个包含
obj.callMe
、obj1.callMe
方法的地方?public delegate void CallEveryOne(); 私人无效Form1_Load(对象发送者,EventArgs e) { 公共 CallEveryOne ptrcall=null; 公共 Form2 obj = new Form2(); 公共 Form3 obj1 = new Form3(); obj.Show(); obj1.Show(); ptrcall += obj.CallMe; ptrcall += obj1.CallMe; }
In the following code, does ptrcall
point...
- to 2 places on the heap with methods
obj.callMe
andobj1.callMe
; or... to 1 place that contains both methods
obj.callMe
,obj1.callMe
within it?public delegate void CallEveryOne(); private void Form1_Load(object sender, EventArgs e) { public CallEveryOne ptrcall=null; public Form2 obj = new Form2(); public Form3 obj1 = new Form3(); obj.Show(); obj1.Show(); ptrcall += obj.CallMe; ptrcall += obj1.CallMe; }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
就像基本上所有从 .NET 2.0 开始的委托一样,ptrcall 是一个多播委托。也就是说,它保留自己所引用的方法的内部列表。 MSDN 在
MulticastDelegate
上有以下说法:因此,用您的术语来说,答案很可能是
ptrcall
指向堆上的 2 个位置。但为什么这个实施细节很重要呢?
PS:您可以调用
ptrcall.GetInvocableList()
并查看返回的结果。我向您推荐这个只是为了更好地了解代表;不要在生产代码中这样做,除非你真的必须。ptrcall
is, like basically all delegates from .NET 2.0 onward, a multicast delegate. That is, it keeps its own internal list of methods that it refers to. MSDN has the following to say onMulticastDelegate
:So, in your terminology, the answer is most likely that
ptrcall
point to 2 place on heap.But why does this implementation detail matter at all?
P.S.: You could call
ptrcall.GetInvocationList()
and see what you get back. I only recommend this to you for toying around and getting to know delegates better; don't do it in production code unless you really have to.我想您想知道与非托管 coe 的互操作吗? Ptrcall 存储对 CallEveryOne 类型(派生自 MulticastDelegate 类型)的对象实例的引用。该对象包含(除其他外)内部数组,其中包含有关添加到该委托的每个方法的信息,但您不打算直接使用它。如果您需要指向订阅方法的指针,请使用 ptrcall.GetInitationList() 获取方法列表,并使用 System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate() 将它们转换为指针。
I suppose you want to know this for interop with unmanaged coe? Ptrcall stores reference to instance of object of type CallEveryOne (that derives from type MulticastDelegate). This object contains (among other things) internal array with information about each method added to this delegate, but you are not intended to use it directly. If you need pointers to subscribed methods, use ptrcall.GetInvocationList() to get list of methods and System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate() to convert them to pointers.