在 .NET 中,委托的内部实现是什么? [英] In .NET, what is the internal implementation of a delegate?

查看:22
本文介绍了在 .NET 中,委托的内部实现是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道委托的声明是这样的:

I understand that a declaration of a delegate is something like this:

public delegate int PerformCalculation(int x, int y);

但是,肯定还有更多事情要做.委托的目的是提供一个指向方法的指针,并为此将对该方法的引用封装在委托中.

However, there must be more going on. The purpose of the delegate is to provide a pointer to a method, and to do that you encapsulate the reference to the method in the delegate.

这个引用保存在什么样的结构中(在委托内部)?我也知道您可以在委托中封装对多个方法的引用.这是否意味着委托中有一个数组来保存这些?

What kind of structure is this reference held in (internally in the delegate)? I also understand that you can encapsulate a reference to multiple methods in a delegate. Does this mean that there is an array in the delegate that holds these?

此外,委托中定义了哪些方法等.当您使用简洁声明委托时真正发生了什么:

Also, what methods are defined in the delegate, etc. What is really happening when you declare a delegate with the terse:

public delegate int PerformCalculation(int x, int y);

?

一些澄清.当您声明一个委托时,编译器会自动为您创建一个继承自 System.MulticastDelegate 的 sealed 类.如果您使用 ildasm 查看您的程序集,您可以看到这一点.这整齐.基本上,通过一个语句,您将在编译时为您生成一个全新的类,它具有您需要的所有功能.

Some clarification. When you declare a delegate, the compiler automatically creates a sealed class that inherits from System.MulticastDelegate for you. You can see this if you look at your assembly with ildasm. This neat. Basically, with one statement, you are getting an entire new class generated for you at compile time, and it has all the functionality you need.

推荐答案

所有委托都继承自 System.Delegate 类型,其中包含 目标方法.更准确地说,它们继承自 System.MultiCastDelegate 继承自 System.Delegate.

All delegates inherit from the System.Delegate type which hold a Target and Method. More precisely they inherit from System.MultiCastDelegate which inherits from System.Delegate.

这篇关于在 .NET 中,委托的内部实现是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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