This article is a mirror article of machine translation, please click here to jump to the original article.

View: 23705|Reply: 1

[Source] C# delegates and various writing methods

[Copy link]
Posted on 3/2/2018 3:35:03 PM | | |
Is it a commission?
A delegate is a type-safe object that points to another method (or methods) in the program that will be called later. In layman's terms, a delegate is an object that can reference a method, and when a delegate is created, it creates an object that references the method, and then the method can be called, that is, the delegate can call the method it refers to.

How do I use delegation?
1. Define the type of entrustment

[access modifier]delegate returns type delegate name (parameter);

2. Declare the entrusted object

Delegate Name The name of the delegated instance;

3. Create a delegation object (determine which method to bind to)

delegate instance name=new delegate name (method of a certain class)

4. Use the entrusted call method

Delegated instance name (parameter)

Precautions for entrustment:1. The delegation and method must have the same parameters.

2、A delegate can call multiple methods, i.e. a delegate can maintain a list of callable methods instead of a single method, known as multicast (multicast)

3、Implement method increases and decreases using += and -= operations

Example:

Writing:

1. Delegate Delegate Name = new Delegate (method name that will be called); Order name (parameter);

2. Delegate Delegate name = method name that will be called; Order name (parameter);

3. Anonymous method

delegate delegate name=delegate(parameter){method body that will be called}; Order name (parameter);

4. Lambda expression

Delegate Order Name=((Parameter 1,。。 parameter n)=>{method body that will be called}); Order name (parameter);

5. Use Action <T>and Func<T>, the first one has no return value

Func< Parameter 1, Parameter 2, Return Value> Delegate Name = ((Parameter 1, Parameter 2) => {Method Body with Return Value }); Return value = order name (parameter 1, parameter 2);

Sticker code:








Previous:Ping multiple locations to check whether the IP address is blocked
Next:ASP.NET WebApi comes with Json and returns date with T cannot be formatted
Posted on 3/5/2018 5:16:17 PM |
Learn to learn
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com