Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
113 views
in Technique[技术] by (71.8m points)

c# - In .NET, what is the internal implementation of a delegate?

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);

?

EDIT: 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.

question from:https://stackoverflow.com/questions/65878401/how-do-i-get-to-the-implementation-code-of-delegates-virtual-method-like-invoke

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...