Current location - Quotes Website - Signature design - How to use delegation in C#?
How to use delegation in C#?
1. Delegation Overview

Delegate is a newly added type in C#. You can think of it as a type similar to Class, similar to using classes. When using delegates, there are two steps. First, you need to define a delegate, just like defining a class. You can then create one or more instances of the delegate.

The syntax for defining a delegate is as follows:

[public/protected/private] delegate returntypedelegatename (param typeparam1,…).

I wrote this myself. It seems a little strange. Let me explain that private/protected/private is a determiner, so I won't say much. Delegate is the keyword to declare the delegate, returnType is the return type, and delegateName is the name you give to the delegate. You can write any name you like, paramtype param 1… This is a list of parameters. Having said that, it may not seem easy to understand. I think so, too. Actually, the delegate definition is to add a delegate keyword to the function definition. Its function is similar to declaring a class:

Common class name {…}

To create an instance of a delegate:

[public/protected/private]delegate name deleInstanceName = new delegate name(method name)

This is similar to instantiating a class, with common class name instance name = new class name (…). One thing to note here is that the MethodName method should be consistent with the signature of delegateName. What is signature consistency? That is to say, the parameter list and return value of MethodName should be consistent with returnType and (paramtype param 1, …) respectively. Let me give you an example to illustrate:

Public delegate string DelegateDemo(string name, Intage);

For example, we defined a delegate as above. In writing, we actually added a Delegate keyword before the function string delegate demo (Intage). Let's create a function:

Common string AgentDemo (string name, integer age)

{

string rev =

Return to rev

}

This function is passed as a parameter to an instance of DelegateDemo, and then an instance of DelegateDemo is created:

delegate name instance demo = new delegate name(agent demo);

At this time, it is necessary to talk about consistency, that is, the return values of AgentDemo and DelegateDemo (let's just remove delegate) should be the same. Finally, I don't know if the people watching it understand.

Next, we can use this delegate (call delegate), as shown below:

string name = " cshape

int age = 20

InstanceDemo (name, age);

When instanceDemo is executed, the AgentDemo function will be executed. InstanceDemo is equivalent to a function pointer in C. Now this pointer points to the function entry address of AgentDemo.

2. Multi-point entrustment

The above delegate contains only a call to a method. If multiple methods need to be called and the delegate needs to be displayed multiple times, we have another option. We can make a delegate contain multiple methods, so that we can call multiple methods in turn by displaying the calling delegate at one time. Please look at the following example:

Public delegate void MultiDelegate (string name);

Public void AgentDemo 1 (string str)

{

Console. WriteLine(str+" this is agentdemo 1 \ n ");

}

Public void AgentDemo2 (string s)

{

Console. WriteLine(s+"This is Agent Demo 2 \ n");

}

multi delegate multi demo = new multi delegate(agentdemo 1);

multi demo+= new multi delegate(agent demo 2);

multi demo(" multi demo test:");

The output should be:

Multimodal testing: This is AgentDemo 1

MutliDemo test: This is AgentDemo2.

You can see that we call one delegate at a time, and it executes methods AgentDemo 1 and AgentDemo2 in turn (according to the order in which you add methods). Here are a few points to note:

● Delegates support operators such as+= and-=, which correspond to adding or removing methods.

Low multipoint delegate can't define a return value, because can't handle the return value of multiple methods, so if you want to use multipoint delegate, you should use void, otherwise your compilation will return an error.

● Multi-point delegation does not recommend that you have the OUT type in the parameter list, so that only the value of the last method will be out, and other values will be lost.

3. Understanding of entrustment

First of all, this is just an example I gave to help understand the process of entrustment, and many of them can't stand scrutiny. I hope you know. Get down to business,

You want to eat,

But I can't do it myself (the client doesn't know the implementation details).

You are going to find a restaurant and order Sichuan style pork and rice (define commission).

You decide to find a restaurant named A that you often go to (instantiation commission).

You call Hotel A (commission call)

Hotel A has prepared Sichuan style pork rice for you (agent).

It's good to have dinner.

4. Timing of using entrustment

When you need to pass one method to another, you can consider using a delegate. It doesn't seem very easy to understand. In other words, when you are sure to deal with one thing, but you are not sure how to deal with it, you can consider using delegation. In fact, it seems a bit far-fetched to say that the application of entrustment is more an application in events.

5. Examples of entrustment

I use two classes to do this example. One class, which I call the client, and the other class, which I call the agent, have the following code:

Use the system;

Namespace Visen Demonstration representative

{

///& lt; Summary & gt

///Start the program entrance in the entrustment demonstration, including the entrusting party.

///& lt; /summary & gt;

Course start-up

{

# Regional public method

The main entry point for the #region application.

///& lt; Summary & gt

///The main entry point of the application.

///& lt; /summary & gt;

[static thread]

Static void Main(string[] args)

{

Console. WriteLine ("This is a commissioned presentation \ n");

Wesson. demo . delegate . Agent ag = new Agent();

//An object that defines the delegate type.

out message single dele = new out message(ag。 show message);

Outmessage delestaticmethod = newoutmessage (proxy. SShowMessage);

//Define multipoint delegation.

out message multi dele = new out message(ag。 show message);

MultiDele += new output message (proxy. SShowMessage);

SingleDele ("delegate instance singledele");

DeleStaticMeth ("delegate instance delestaticmeth");

MultiDele ("This is a multielement");

Console. read();

}

The main entry point for the #endregion application.

#endregion public method

# Zone Private Field

///& lt; Summary & gt

///Define the delegate type.

///& lt; /summary & gt;

Private delegate void OutMessage (string msg);

#endregion private field

}

}

The following are agents:

Use the system;

Namespace Visen Demonstration representative

{

///& lt; Summary & gt

/// Agent class is the principal's agent, which handles the affairs entrusted by the principal.

///& lt; /summary & gt;

Public collective agency

{

# Regional public method

Constructor of #region null

///& lt; Summary & gt

///empty constructor

///& lt; /summary & gt;

Public agency ()

{

}

#endregion null constructor

#region displays messages to the console, and class member functions act as proxies.

///& lt; Summary & gt

///Use the class member function as a proxy to display messages to the console.

///& lt; /summary & gt;

///& lt; Param name = "msg"> display content

Public void ShowMessage (string message)

{

Console. WriteLine(" Method show message out:"+msg+" \ n ");

}

#endregion displays a message to the console, and the class member function acts as a proxy.

#region displays a message to the console, and a class static function acts as a proxy.

///& lt; Summary & gt

///Displays messages to the console and uses class static functions as proxies.

///& lt; /summary & gt;

///& lt; Param name = "msg"> display information.

Public static void SShowMessage (string message)

{

Console. WriteLine(" static Method SShowMessage out:"+msg+" \ n ");

}

#endregion displays a message to the console, using class static functions as proxies.

#endregion public method

}

}

The output is:

This is a representative demonstration.

Method ShowMessage out: delegate instance singleDele.

Static method ShowMessage out: delegate instance deleStaticMeth

Method ShowMessage out: this is a multi-element

Static method ShowMessage out: this is a multi-element

It can be seen that the method function can be a class member function or a static member, as long as it is the same as the signature of the delegate.

If there are any mistakes, please criticize and correct them. Thank you!