Where does delegates' constructors and member

2019-01-28 16:37发布

问题:

When I was looking at the Action delegates in Reflector, I saw it has a constructor like

public Action(object @object, IntPtr method);

But I could not find any body for the same along with other member functions like Invoke, BeginInvoke etc. I can only see the definitions for it. Where does these functions are defined? Are they defined outside of the .net BCLs?

回答1:

Delegates are handled specially by the CLR, basically. The compiler provides the signatures, but the CLR knows what to do with them.

Section 8.9.3 of ECMA-335 partition I talks about this:

Delegates are the object-oriented equivalent of function pointers. Unlike function pointers, delegates are object-oriented, type-safe, and secure. Delegates are created by defining a class that derives from the base type System.Delegate (see Partition IV). Each delegate type shall provide a method named Invoke with appropriate parameters, and each instance of a delegate forwards calls to its Invoke method to one or more compatible static or instance methods on particular objects. The objects and methods to which it delegates are chosen when the delegate instance is created.

In addition to an instance constructor and an Invoke method, delegates can optionally have two additional methods: BeginInvoke and EndInvoke. These are used for asynchronous calls.

While, for the most part, delegates appear to be simply another kind of user-defined class, they are tightly controlled. The implementations of the methods are provided by the VES, not user code. The only additional members that can be defined on delegate types are static or instance methods.

(VES is the Virtual Execution System; the CLR is Microsoft's implementation of the VES.)