在.NET中,什么是委托的内部实现?NET

2023-09-03 10:08:22 作者:Grind(折磨)

据我所知,委托的声明是这样的:

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为您服务。你可以看到这个如果你用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.