C # Not a C ++ Delegate (Delegate)

Source: Internet
Author: User

Recently, I spoke to the project team and met some students who have just graduated from school. I claim to be proficient or even proficient in C #. At the beginning, every time I read my resume that says "proficient in C #", I feel an inexplicable excitement. However, the results are often disappointing. After several such experiences, I found that some resumes have too much moisture, and most of them are really skilled, but not C #, but C ++. In other words, what they are "proficient" is the part taught by the school. The different parts of C # And C ++ are very unfamiliar, even just "heard of them ".

During the interview, you often have to ask a very simple question. You can see that the interviewee is familiar with C.

For example, you can see your understanding of the delegate syntax by asking the examinee to write a delegate.

Okay. Let's get started with the question. What is commission? What is the essence of delegation?

In the course of C ++ learning, you will surely be exposed to a variety of pointers, one of which is pointing to a function or method, we can call this pointer to call the method it points. However, such a pointer is insecure. If we simply regard the C ++ pointer as a space to record the memory address, the method pointer records the call address of the target method. However, C ++ does not impose any restrictions on the object to which the Pointer Points. You do not know what the method will return or how many parameters the method will receive, you do not know the type of the received parameter, and in C ++, the pointer can also be involved in the operation. Therefore, for callers, apart from seeing an address, the rest are unknown. It is only after the call. Such pointers are often used by malformed people to point the method pointer to a method that destroys the system ...... It's like giving you a key to open a box. What is in the box? Maybe it's a cake, maybe it's Pandora's box ...... Who knows. :-)

Due to imperfect method pointers, C # has improved this phenomenon-delegate. The role of a delegate is the same as a method pointer. It is used to point to a method and provided to the client program for calling. However, this method pointer is restricted. It must specify the return values, number of parameters, and types of parameters pointing to the method. Therefore, this "key" can open the cake box but cannot open Pandora's box ...... Well, it feels much safer.

Therefore, the so-called delegate refers to the method pointer that determines the signature of the target method-if you think that the pointer concept in C # has been eliminated, then, okay, let's change the argument: the so-called delegate refers to a special object that can call the target method and determine the target method signature. ^ O ^

In C # syntax, delegation can be divided into two types: Delegation statement and delegation instance, and both of them can be referred to as delegation at the same time. Therefore, when we talk about delegation, we need to judge whether a delegation refers to the delegation statement or the delegated instance based on the context.

The delegate Statement, which is used to declare the signature of the method pointed to by the delegate (instance. It starts with the delegate keyword and is followed by the method signature. For example, when I want to point to the method:

public string MergeString(string s1, string s2)

We can declare a string with two parameters and return a string delegate:

delegate string TestDelegate(string s1, string s2);

The delegate Declaration itself does not point to any method, so it cannot be called directly. However, we can instantiate an object through a delegate (Declaration), so that the object is called a delegate instance. The creation of the delegated instance is similar to the instantiation of an object with a class, but there is a convention that the method name of the target method should be passed in as a parameter, for example:

public void Print(string s1, string s2)
{
TestDelegate testDelegate = new TestDelegate(MergeString);
string newString=testDelegate(s1, s2)
Console.WriteLine(newString);
}

In the first line of method Print, we obtain a delegate instance using a delegate statement. The second line calls this delegate. The third line is output. That's simple.

Well, in summary, the essence of delegation is a secure method pointer. The delegation is divided into delegate statements and delegate instances. When using the delegate, the delegate is declared first, then instantiated, and finally called.

Now there is an interesting question: why do we need to use delegation? In this example, I will not only write the entire method, but also declare the delegate and instantiate it ...... Why is it so complicated? What do we bring with delegated write?

When entrusting brings us the biggest benefit: it can call other methods dynamically through programming methods. What does this mean? This means that when we use the delegate as a parameter, we can write a code template so that it can execute different code in a certain way. Example:

We have an existing method to print the current time:

public void PrintTime()
{
Console.WriteLine(DateTime.Now.ToString("HH:MM:ss"));
}

 

We have another method to print the current date:

public void PrintDate()
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd"));
}

Coincidentally, or unfortunately, in the current program, both methods need to be called cyclically. Then, we can use a method to encapsulate this loop, to avoid endless write loops in the program:

public static void MultipleRun(RunOnce method, int count)
{
for (int i = 0; i < count; i++)
{
method();
}
}

 

Well, the next thing is to call it as much as possible. How about 1000 times each?

TestClass tc = new TestClass();
MultipleRun(tc.PrintDate, 1000);
MultipleRun(tc.PrintTime, 1000);

If you are not satisfied, change the parameter ^ o ^.

Finally, paste a complete, simple to meaningless sample source code ^ _ ^:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication4
{
class Program
{
delegate void RunOnce();
private static void MultipleRun(RunOnce method, int count)
{
for (int i = 0; i < count; i++)
{
method();
}
}

static void Main(string[] args)
{
TestClass tc = new TestClass();
MultipleRun(tc.PrintDate, 1000);
MultipleRun(tc.PrintTime, 1000);
}
}

class TestClass
{
public void PrintTime()
{
Console.WriteLine(DateTime.Now.ToString("HH:mm:ss"));
}

public void PrintDate()
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd"));
}
}
}

 

Welcome to the discussion!

Related Article

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.