Example of delegate instance code in C # (graphic)

Source: Internet
Author: User
This article mainly introduces the related knowledge of delegation in C #. Have a certain reference value, follow the small series below to see it

Commissioned this thing is not very good understanding, but often used in the work, you can see it everywhere, really let people have a love and hate feeling, I believe that many people have been troubled by it.

When it comes to delegation, if you have learned C, you will immediately associate a function pointer.

What is a delegate? Delegates are type-safe in C # and can subscribe to one or more function pointers with the same signature method. A delegate can pass a function as a parameter, and its practical meaning is to let someone else act on your behalf. A delegate can be seen as a pointer to a function, an integer can point to it with an integer variable, and an object can point to it with an object variable.

A function can also point to it with a delegate variable. We can choose to consider a delegate type as an interface that defines only one method, while an instance of a delegate can be seen as an object that implements that interface.

With a delegate, 4 conditions must be met:

    • declaring the delegate type;

    • There must be a method that contains the code to be executed;

    • A delegate instance must be created;

    • The (Invoke) delegate instance must be called.

Declaration of Delegation

How to declare a delegate: Delegate return value type delegate type name (parameter)

The declaration of the Delegate and the statement of the interface method are basically the same, except that there is a delegate keyword in front of the return type keyword. There is also a delegate that is generally declared as a public type because it is ready for others to invoke.

The nature of a delegate is also a type. We declare that a class can be instantiated, and the same delegate can be instantiated.

There are four types of delegates:

1. No parameter no return value public    delegate void Noparanoreturneventhandler ();    2. Parameter no return value public    delegate void Withparanoreturneventhandler (string name);    3. No parameter has return value public    delegate string Noparawithreturneventhandler ();    4. Parameters have a return value of public    delegate string Withparawithreturneventhandler (string name);

Delegates can generally be used if the code wants to perform operations but does not know the details of the operation. For example, the only reason the thread class knows what to run in a new thread is to provide it with a ThreadStart or Parameterizedthreadstart delegate instance when the new thread is started.

Thread th = new Thread (Test); th. Start ();p ublic Thread (threadstart start);p ublic delegate void ThreadStart ();

ThreadStart is a delegate with no parameter and no return value.

    static void Test ()    {      Console.WriteLine ("Threading Method");    

The function signature of this test method must be the same as the function signature of the delegate ThreadStart.

Invocation of a delegate

The delegate must be instantiated before it can be called.

The signature of the function and the signature of the delegate must be identical. Noparanoreturneventhandler _noparanoreturneventhandler = consoleinfo; the compiler helped us with new, but could not write Noparanoreturneventhandler _noparanoreturneventhandler = Consoleinfo ();

Because this becomes a function call.

#region no return value delegate calls public    static void Show ()    {      //instantiation Delegate      Noparanoreturneventhandler _ Noparanoreturneventhandler = new Noparanoreturneventhandler (consoleinfo);      Noparanoreturneventhandler _noparanoreturneventhandler = Consoleinfo;      the shorthand//delegate call is invoked via Invoke (), or the      _noparanoreturneventhandler.invoke () can be omitted directly;      _noparanoreturneventhandler ();    }    private static void Consoleinfo ()    {      Console.WriteLine ("No function call with no parameter return value");     #endregion

Without a delegate there is no async, and Async is because of the existence of a delegate.

_noparanoreturneventhandler.begininvoke (Null,null); asynchronous invocation

Why do you use delegates

We can simply invoke the method, why do we need to invoke it through a delegate? What is the point of entrusting?

Decoupling, closed for modification, open for expansion. Logical separation.

You can interpret a delegate as a parent of a function, or as a placeholder for a method.

Let's look at the code, assuming there are 2 methods, one speaking English, one speaking Chinese, and the function signature of the 2 methods is the same.

public static void Saychinese (string name)    {      Console.WriteLine ("Hello," + name);    }    public static void Sayenglish (string name)    {      Console.WriteLine ("Hello," + name);    }

So when we call outside,

  Mydelegate.saychinese ("Zhang San");  Mydelegate.sayenglish ("Zhangsan");

If you want to call these two different methods, is not to write a different calling code

Can we just call it one method? Modify the code as follows:

public static void Say (String Name,withparanoreturneventhandler handler)    {      handler (name);    }   public static void Saychinese (string name)    {      Console.WriteLine ("Hello," + name);    }    public static void Sayenglish (string name)    {      Console.WriteLine ("Hello," + name);    }

In this way, the call is made only through a method say.

How do I call it? Here are three ways to call:

      Withparanoreturneventhandler _withparanoreturneventhandler = new Withparanoreturneventhandler ( Mydelegate.saychinese);      Mydelegate.say ("Zhang San", _withparanoreturneventhandler);      Mydelegate.say ("Zhang San", Delegate (string name) {Console.WriteLine ("Hello," + name);}); anonymous method      Mydelegate.say ("Zhang San", (name) = = {Console.WriteLine ("Hello," + name);});//lambda expression

The above code uses several invocation methods, which are constantly optimized as C # is upgraded. The first is the traditional calling method in c#1.0, the second is the anonymous method invocation in c#2.0, the so-called anonymous method, which is the method with no name, when the method is called only once, the use of anonymous method is most appropriate. The lambda expression in c#3. In fact, generic delegates are also supported, and. NET 3.5 goes a step further by introducing a set of generic delegate types called Func that can fetch multiple parameters of a specified type and return a value of another specified type.

Lambda expression

The essence of a lambda expression is a method, an anonymous method.

If the method body has only one row and no return value, you can also remove the curly braces and semicolons.

MyDelegate.Say("张三", (name) => Console.WriteLine("你好," + name));

If the method body has only one row and there is a return value, you can remove the curly brace and return.

WithParaWithReturnEventHandler _WithParaWithReturnEventHandler = (name)=>name+",你好";

Starting with. NET3.5, we basically don't need to declare our own mandate because the system has many built-in delegates.

The action and Func delegates have 16 and 17 overloads, respectively. int represents the input parameter, out represents the return value, and the out parameter is placed at the end.

The action represents a delegate with no return value, and Func represents a delegate with a return value. Because the method is classified from a large angle, it is also divided into the method of returning value and the method of no return value.

That is to say what method to call, completely by the caller decide, there is more flexibility and extensibility. Why do you say that, if I have to speak English some time before the Chinese, some things to speak Chinese speaking English, if there is no delegation, how will we achieve? Take a look at the following code:

public static void Sayenglishandchinese (string name)    {      sayenglish (name);      Saychinese (name);    }    public static void Saychineseandenglish (string name)    {      Saychinese (name);      Sayenglish (name);    }

What if you suddenly want to add a Russian? The callee code has to be modified, so the loop goes on, is it going to freak out? As new languages are added, the code becomes more complex and more difficult to maintain. Such code coupling is very high, it is unreasonable, that is, the so-called Code of Bad taste, you can design patterns (such as observer patterns, etc.), do not use the delegate to refactor the code, but the implementation is very cumbersome, to write a lot more code ...

Delegates can pass methods that can represent a series of operations that are determined by the caller, are well expanded, and are flexible. Instead of modifying existing methods, we extend them only in the form of added methods.

Maybe some people will say, I come directly to the caller to a call I want to implement which methods like to achieve this effect ah?

But have you ever thought that you are going to invoke a series of methods that you simply cannot reuse in this series of methods. The use of a delegate is different, it is like a collection of methods of the container, you can add and subtract methods, can be reused. And with delegates, you can delay the invocation of the method list, and you can add or subtract the list of methods at any time. The delegate has once again encapsulated the method.

Summary: that is, when you can only determine the method of the function signature, can not determine the specific implementation of the method, in order to be able to better expand, in the form of a similar injection method to achieve new functions, can reflect the value of the delegate.

the difference between a delegate and a direct call function: A delegate can point to any function, even if it is not defined before, without being limited to which.

Multicast delegation

The combined delegate must be of the same type, which is equivalent to creating a new delegate object that is called sequentially in the combined order. The combination of delegates is usually used for events, and is seldom used with ordinary delegates.

The method is added to the delegate instance through +,-to remove the method from the delegate instance.

+ and-is purely to simplify the code, and in fact its invocation is the Delegate.combine method and the Delegate.remove.

If there are multiple methods with return values in the delegate, the return value of the calling delegate is the return value of the last method.

public static void Multipleshow ()    {      //multicast delegate      Noparawithreturneventhandler _noparawithreturneventhandler = New Noparawithreturneventhandler (getdatetime);      _noparawithreturneventhandler + = GetDateTime;      Console.WriteLine (_noparawithreturneventhandler ());    }    public static string GetDateTime ()    {      return string. Format ("Today is the {0} number. ", DateTime.Now.Day.ToString ());    }

Commission Summary:

    • A delegate encapsulates a behavior that contains a special return type and a set of parameters, similar to an interface that contains a single method;

    • The type signature described in the delegate type declaration determines which method can be used to create the delegate instance, while determining the signature of the call;

    • In order to create a delegate instance, a method is required and (for instance methods) The target of the method is called;

    • The delegate instance is not immutable, just like a string;

    • Each delegate instance contains a list of calls-a list of actions;

    • An event is not a delegate instance-it is just a paired Add/remove method (similar to a property's accessor/assignment method).

Common usage scenarios: Form pass-through values, thread-start binding methods, lambda expressions, async, and so on.

Examples of life: Now not everyone is robbing train tickets, using the cloud to rob votes is equivalent to the use of the Commission, you can directly buy tickets, you can also be hosted in the cloud to rob tickets, their own ticket, in the near-fire, you must always refresh, the next single-pass verification code and so on, you just put the ticket before, Enter the ticket information in advance, you will no longer need your tube, automatic ticketing, you do not need to know how the cloud to rob the ticket over there is how to help you achieve the ticket. The same time and train can be made a delegate instance, a lot of people through this delegate instance to rob ticket operation.

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.