C # basic enhancement-delegate, Lamada expressions, and events (I ),

Source: Internet
Author: User

C # basic enhancement-delegate, Lamada expressions, and events (I ),

1. Delegate

The C # delegate is equivalent to the function pointer in C/C ++. Function pointers use pointers to obtain the entry address of a function to perform operations on the function.

Unlike the function pointer in C/C ++, a delegate is object-oriented and a reference type. The use of a delegate must be defined and instantiated before it can be called. The delegate is type-safe. It defines the return type and parameter type. In C/C ++, the function pointer is just a pointer to the memory location, it is not type-safe. We cannot determine what the pointer actually points to, so the parameters and return types cannot be known.

Define Delegation

Use the keyword delegate. The syntax is similar to the definition of a method, but there is no method body. The keyword delegate is added before the definition.

For example, define a delegate: delegate void IntMethod (int x );

In this example, a delegate IntMethod is defined and each instance of the delegate can contain a reference to the method. This method has an int parameter and the return type is void.

If you want to define a delegate TwoLongOp, the delegate represents two long-type parameters, and the return type is double, you can define it as delegate double TwoLongOp (long first, long second );

Delegate string GetString (); // No parameter is set for the method represented by this delegate. The string type is returned.

The definition delegate is basically a new class, which can be defined anywhere in the definition class. That is to say, you can define the delegate as a top-level object in the namespace, either in the internal definition of a class or in the external definition.

You can apply access modifiers such as public, protected, and private in the definition of a delegate to limit the scope of the delegate. Example: public delegate void IntMethod (int x );

Instantiate and call

1 private delegate string GetString (int x); // define delegate 2 static void Main (string [] args) 3 {4 GetString strMed = new GetString (StringMethod ); // instantiate the delegate and initialize the 5 Console. writeLine (strMed (555); // call delegate 6 Console. readKey (); 7} 8 private static string StringMethod (int x) 9 {10 return x. toString (); 11}

Note: in C #, the delegate always accepts the constructor of a parameter. this parameter is the method referenced by the delegate. This method must match the signature of the delegate definition. In this example, when the delegate is defined, the return type is string and the parameter type is int. Therefore, the StringMethod must be the same when the strMed variable is initialized.

There are two different terms for a class. "Class" indicates a wide range of definitions, and an object indicates an instance of the class. However, there is only one term for delegation. When you create a delegated instance, the created delegated instance is still called a delegate.

You can also directly assign the method referenced by the delegate to the delegate type variable (delegate inference), for example, GetString strMed = StringMethod;

Action <T> and Func <T> delegate

This further simplifies the definition of the delegate without explicitly declaring the custom delegate.

A generic Action <T> delegate refers to a void return type method. This delegate class has different variants and can be passed up to 16 different parameter types. Action classes without generic parameters call methods without parameters.

Public delegate void Action () public delegate void Action <in T> (T obj)

......

 1    static void Main(string[] args) 2         { 3             Action<string> messageTarget; 4             messageTarget = GetAStr; 5             messageTarget("Action<T> Demo!"); 6             Console.ReadKey(); 7         } 8         private static void GetAStr(string obj) 9         {10             Console.WriteLine(obj);11         }

Func <T> allows calling methods with return types. Similar to Action <T>, different variants are defined, up to 16 different parameter types and one return type can be passed.

Public delegate TResult Func <out TResult> ()

Public delegate TResult Func <in T, out TResult> (T arg)

Public delegate TResult Func <in T1, in T2, out TResult> (T1 arg1, T2 arg2 )......

1 public static void Main () 2 {3 Func <string, int, string []> extractMethod = ExtractWords; // The last one is the type of the return value. The previous one is the type of the parameter. 4 string str = "helloawordaFunc"; 5 foreach (string word in extractMethod (str, 5) 6 Console. writeLine (word); 7} 8 private static string [] ExtractWords (string phrase, int limit) 9 {10 char [] delimiters = new char [] {'A '}; 11 if (limit> 0) 12 return phrase. split (delimiters, limit); 13 else14 return phrase. split (delimiters); 15}

 

Multicast Delegation

Multiple methods are called by a delegate at a time. The + and-operators are used to increase or decrease multicast. Multicast delegates include the list of assigned delegates. When a multicast delegate is called, it calls the delegate in the list in sequence. Only delegates of the same type can be merged.

 1     static void Main(string[] args) 2         { 3             Action del = D1; 4             del += D2; 5             del += D3; 6             del(); 7             Console.WriteLine("------------------"); 8             del -= D2; 9             del();10             Console.ReadKey();11         }12         private static void D1()13         {14             Console.WriteLine("I am D1");15         }16         private static void D2()17         {18             Console.WriteLine("I am D2");19         }20         private static void D3()21         {22             Console.WriteLine("I am D3");23         }

Msdn example:

 1   static void Hello(string s) 2     { 3         System.Console.WriteLine("  Hello, {0}!", s); 4     } 5     static void Goodbye(string s) 6     { 7         System.Console.WriteLine("  Goodbye, {0}!", s); 8     } 9     static void Main()10     {11       12         CustomDel hiDel, byeDel, multiDel, multiMinusHiDel;13         hiDel = Hello;14 15         byeDel = Goodbye;16 17         multiDel = hiDel + byeDel;18 19         multiMinusHiDel = multiDel - hiDel;20 21         Console.WriteLine("Invoking delegate hiDel:");22         hiDel("A");23         Console.WriteLine("Invoking delegate byeDel:");24         byeDel("B");25         Console.WriteLine("Invoking delegate multiDel:");26         multiDel("C");27         Console.WriteLine("Invoking delegate multiMinusHiDel:");28         multiMinusHiDel("D");29     }

 

Lamada expressions and events will be introduced in the next section ....

 

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.