C #: Delegate)

Source: Internet
Author: User

1. Delegate: a reference to a type-safe method. The parameter signature and returned data type of the method represented by the delegate are determined when the delegate is defined. Therefore, the delegate is type safe, which is completely different from the pointer.

The use of the delegate is basically the same as that of the class. The use of the delegate is divided into three steps: 1. Delegate Declaration; 2. Delegate instantiation; 3. Delegate call.

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; using System.Collections;namespace ConsoleApplication{    class Program    {        delegate string GetString();
        static void  Main(string[] args)        {             string str="HelloWorld";             GetString dlg=new GetString(str.ToString);             Console.WriteLine("str.ToString():".PadRight(20) + str.ToString());             Console.WriteLine("dlg:".PadRight(20) + dlg);             Console.WriteLine("dlg():".PadRight(20) + dlg());                   Console.ReadKey();        }    }}

 

Note the following points for delegation:

① When a method is bound to a delegate, the name of the method is used, that is, it cannot contain parentheses;

② The call delegate must contain parentheses;

 

2. Action <t> and func <t> delegates

This is a special generic delegate. Action <t> is a delegate without a return value. It can contain at least 0 parameters and a maximum of 16 parameters; func <t> is a delegate with a return value. The last type parameter is the type of the return value. It can contain at least 0 parameters and a return value. It can contain up to 16 parameters and a return value.

Example: Action <int, string>

The method represented by this delegate has two parameters, the first parameter type is int type, the second parameter type is string type, and no return value.

Func <int, string>

The method represented by this delegate has a parameter. The value type of this parameter is int type, and the return value type is string type.

 

Iii. multicast delegates)

A delegated instance can bind a single method or multiple methods. The delegate for binding a single method is called singlecast delegetes. The delegate for binding multiple methods is called multicast delegates ).

The delegate supports the +,-, + =,-= Operator. Therefore, the two delegate can be directly added or subtracted to generate a new multi-channel broadcast delegate. + Operation or + = operation is to bind the new method to the delegate.-operation or-= means to unbind the method from the delegate. The execution sequence of the method bound to a multicast delegate is the same as that of the method bound to the delegate. However, if an exception is thrown by a method during execution, subsequent methods cannot be executed. If you want to smoothly execute the subsequent methods even if an exception occurs during the execution of the Delegate-bound method, you can use the getinvocationlist () method, perform the methods sequentially, and catch exceptions. For example:

        static void Main()        {            Action d1 = One;            d1 += Two;            Delegate[] delegates = d1.GetInvocationList();            foreach (Action d in delegates)            {                try                {                    d();                }                catch (Exception)                {                    Console.WriteLine("Exception caught");                }            }            Console.ReadKey();        }        static void One()        {            Console.WriteLine("One");            throw new Exception("Error in one");        }        static void Two()        {            Console.WriteLine("Two");        }

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.