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