I have been doing .NET development for a long time, and recently reviewed the book "C# Advanced Programming". I found that many problems that I once seemed to understand but did not understand can actually be slowly studied and understood.
So, I plan to start writing a blog post on the "C# Advanced Programming Series". It will draw on the concept of the book "C# Advanced Programming", and will also refer to the blog posts of other experts, I hope you understand. If there is something wrong, please correct it.
(Also: This blog post will not explain the basics of definitions and grammar.) )
Let's talk about commissioning.
Delegate is widely used in .NET. Lambda expressions, events, anonymity methods, etc. will be involved (stay tuned for subsequent blog posts).
So what is entrustment?
In layman's terms, delegates are no different from specifying methods except that they must specify the delegate keyword and have no method entity. You can think of it as a placeholder, for example, when you write code without knowing what you're going to deal with. You just need to know what the parameter type and output type you are going to introduce are and define it. This is the method conveyed in the book that the signature must mean the same.
Let's define a basic delegation:
Execution results:
Do you see the above practical place to entrust? NamelyA delegate can execute any method with the same ingestion parameter type and return type, or even a method queue with the same signature.
So do our method signatures (i.e. import and output parameters) really have to be exactly the same as the delegate? Answer: No, we cannot ignore covariance and inverse variation. Let's briefly introduce the knowledge of covariant and inverter.
"Covariance" means being able to use a type that is more derived than the originally specified derived type. "Inverter" refers to the ability to use a type with a smaller degree of derivation. Then, our commission is also subject to covariance and inverse.
This means that if a delegate is defined, not only the exact same signature method can assign value to the delegate variable.
If a method's parameter table matches the delegate declaration, but returns a derived class of (the delegate declaration returns the type), then the method can also be assigned to this delegate variable.
If the return type of a method matches the delegate's declaration, but the argument is the ancestor class of the delegate declaration parameter type, then the method can also be assigned to the delegate variable.
If the parameters and return type of a method match the assumptions in the above two lines, then the method can also be assigned to the delegate variable.
The following is a simple example of covariant vs. inverter:
Covariance:
Inverter:
|