How are delegates used in C #? Reprint

Source: Internet
Author: User

1. Delegation overview
A delegate is a newly added type in C # that you can think of as a type similar to class, similar to using a class, with a delegate that takes two steps, first you define a delegate as if it were a class, and then you can create one or more instances of the delegate.
The syntax for defining a delegate is this:
[Public/protected/private] Delegate returntype delegatename (paramtype param1,...)
This is my own writing, it seems a little strange, I would like to explain, Private/protected/private is a qualifier, not much to say, delegate is to declare a delegate keyword, returntype is a return type, Delegatename is a name you entrust, you can write any name you like, Paramtype param1 ... This is the parameter list. Said so much may seem to be still not very good understanding, I think so, practical point, the delegate definition is to add a delegate keyword in the middle of a function definition. It acts like you declare a class:
public class ClassName {...}
To create an instance of a delegate:
[Public/protected/private] delegatename deleinstancename = new Delegatename (MethodName)
This is similar to instantiating a class, public ClassName instancename = new ClassName (...), here is a place to note that the MethodName method is consistent with the delegatename signature. What is the signature consistent, that is, the MethodName parameter list, the return value to be returntype, (Paramtype param1,...) Consistent. Let's take an example to illustrate the following:
Public delegate string Delegatedemo (string name, int.);
For example, if we define a delegate, in terms of writing, it is actually adding a delegate keyword in front of the function string Delegatedemo (string name, int age), let's create a function:
public string Agentdemo (string name, int age)
{
String rev = "";
...
return rev;
}
This function is passed to a Delegatedemo instance, and then an instance of Delegatedemo is created:
Delegatename Instancedemo = new Delegatename (Agentdemo);
At this point we have to say the same, that is, the Agentdemo and declaration of the delegate Delegatedemo (we will delegate remove) the return values of the two functions, the parameter list is the same. Finally finished, do not know the people who see do not understand.
Next, we can use this delegate (call a delegate), as follows:
String name = "Cshape";
int age = 20;
Instancedemo (name, age);
When Instancedemo executes, the Agentdemo function is executed, instancedemo equivalent to a function pointer in C, which now points to the Agentdemo function entry address.
2. Multi-Point delegation
The previously mentioned delegate contains only a call to a method, if more than one method needs to be called, we have another option, we can have multiple methods in a delegate, so that we can display the invocation delegate at a time, and then sequentially call multiple methods in sequential order. Look at the following example:
public delegate void Multidelegate (string name);
public void AgentDemo1 (String str)
{
Console.WriteLine (str + "This is agentdemo1\n");
}

public void AgentDemo2 (string s)
{
Console.WriteLine (S + "This is agentdemo2\n");
}

Multidelegate Multidemo = new Multidelegate (AGENTDEMO1);
Multidemo + = new Multidelegate (AGENTDEMO2);
Multidemo ("Multidemo test:");

The result of the output should be:
Multidemo Test:this is AgentDemo1
Mutlidemo Test:this is AgentDemo2

You can see that we show a delegate at a time, and it executes the methods AgentDemo1 and AgentDemo2 sequentially (in the order in which you added the method). Here are a few things to note:
The delegate supports an operator such as +=,-=, which corresponds to adding or removing a method
A multipoint delegate cannot define a return value because the return value of multiple methods cannot be processed, so if you want to use a multipoint delegate, you should use void, or your compilation will return an error
The multipoint delegate does not recommend that you have an out type in the argument list, so that only the value of the last method is out, and the other values are lost.
3. Understanding of the delegation
First of all, this is just an example of my intention to help understand the process of commissioning, many of which cannot withstand scrutiny. Anyway
You want to eat,
But I can't do it (the client doesn't know the implementation details),
You plan to find a restaurant and call a cooked meal (define a delegate)
You decided to go to the restaurant that you used to call a. (instantiation of a delegate)
You call the A hotel (delegate call)
A hotel for you to make your cooked pork meal (agent function work)
It's good to have dinner.

4. Time of use of the delegate
When you need to transfer a method to another method, consider using a delegate. It doesn't seem to be a good idea, but you can say that when you're sure you want to deal with one thing, but you're not sure how to handle it, you can consider using a delegate. In fact, the application of the delegate is a bit far-fetched, commissioned more in the event of the application.
5. An example of a delegate
I use two classes to do this example, a class, I call it the principal, a class I call it the agent, the code is as follows:
Using System;

Namespace Visen.Demo.Delegate
{
<summary>
The program entry in the StartUp delegate demonstration, including the principal party.
</summary>
Class StartUp
{
#region公用的方法

#region应用程序的主入口点.
<summary>
The main entry point for the application.
</summary>
[STAThread]
static void Main (string[] args)
{
Console.WriteLine ("This is a delegate demo\n");

Visen.Demo.Delegate.Agent AG = new Agent ();

An object that defines a delegate type
Outmessage Singledele = new Outmessage (AG. ShowMessage);
Outmessage Delestaticmeth = new Outmessage (agent.sshowmessage);

Define a multi-point delegate
Outmessage Multidele = new Outmessage (AG. ShowMessage);
Multidele + = new Outmessage (agent.sshowmessage);

Singledele ("delegate instance Singledele");
Delestaticmeth ("delegate instance Delestaticmeth");
Multidele ("This is a Multidele");
Console.read ();
}
#endregion应用程序的主入口点.

#endregion公用的方法

#region私用的字段
<summary>
Define a delegate type
</summary>
Private delegate void Outmessage (string msg);
#endregion私有的字段
}
}

Here are the agents:
Using System;

Namespace Visen.Demo.Delegate
{
<summary>
The agent class is the proxy of the delegate and handles the transaction entrusted by the delegate.
</summary>
public class Agent
{
#region公用的方法

#region空的构造函数
<summary>
An empty constructor
</summary>
Public Agent ()
{
}
#endregion空的构造函数

#region显示一条信息到控制台, a class member function acts as a proxy
<summary>
Displays a message to the console, a class member function as a proxy
</summary>
<param name= "MSG" > Display content </param>
public void ShowMessage (String msg)
{
Console.WriteLine ("Method showmessage out:" + msg + "\ n");
}
#endregion显示一条信息到控制台, a class member function acts as a proxy

#region显示一条信息到控制台, a class static function acts as a proxy
<summary>
Display a message to the console, a class static function acting as a proxy
</summary>
<param name= "MSG" > Display information </param>
public static void Sshowmessage (String msg)
{
Console.WriteLine ("Static Method Sshowmessage out:" + msg + "\ n");
}
#endregion显示一条信息到控制台, a class static function acts as a proxy

#endregion公用的方法
}
}
The output is:
This is a delegate demo

Method ShowMessage Out:delegate Instance Singledele

Static Method sshowmessage Out:delegate instance Delestaticmeth

Method ShowMessage Out:this is a Multidele

Static Method Sshowmessage Out:this is a Multidele

Visible: A method function can be a class member function or a static member, as long as the signature of the delegate is the same.

Http://zhidao.baidu.com/link?url=6r_4M47uClupVFDJgs-g9dOgZTrGh1yrYRGoqkMDymN_kGcYEANiQpkVLQ42qVihAH-oAq7xZjSr-9vlUQaPVK

How are delegates used in C #? Reprint

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.