C # delegate introduction (delegate, Action, Func, predicate ),

Source: Internet
Author: User

C # delegate introduction (delegate, Action, Func, predicate ),
A delegate is a class that defines the type of a method so that the method can be passed as a parameter of another method. An event is a special delegate.

1. Delegate statement

(1). delegate

Delegate is a common declaration.

Delegate has at least 0 parameters and up to 32 parameters. The return value type can be specified or not.

For example, public delegate int MethodtDelegate (int x, int y); indicates that there are two parameters and int type is returned.

(2). Action

Action is a generic delegate without return values.

Action indicates a delegate with no parameter and no return value.

Action <int, string> indicates that the input parameter int exists, and the string value does not return a delegate.

Action <int, string, bool> indicates that the input parameters int, string, and bool have no return value.

Action <int, int> indicates that four int-type parameters are input and no delegate is returned.

Action has at least 0 parameters, up to 16 parameters, and no return value.

Example:

        public void Test<T>(Action<T> action,T p)        {            action(p);        }

(3). Func

Func is a generic delegate with a returned value.

Func <int> indicates that there is no parameter, and the return value is the delegate of int.

Func <object, string, int> indicates that the input parameter is an object, and the string return value is an int delegate.

Func <object, string, int> indicates that the input parameter is an object, and the string return value is an int delegate.

Func <T1, T2, T3, int> indicates that the input parameter is T1, T2, and T3 (generic), and the return value is the int delegate.

Func has at least 0 parameters and up to 16 parameters. Return results based on the returned value of the generic type. There must be a return value, not void

Example:

        public int Test<T1,T2>(Func<T1,T2,int>func,T1 a,T2 b)        {            return func(a, b);        }

(4). predicate

Predicate is a generic delegate that returns the bool type.

Predicate <int> indicates that the input parameter is int and the bool delegate is returned.

Predicate has only one parameter, and the return value is fixed to bool.

Example: public delegate bool Predicate <T> (T obj)

  

 2. Use of delegation

  (1) Use of Delegate

        public delegate int MethodDelegate(int x, int y);        private static MethodDelegate method;        static void Main(string[] args)        {            method = new MethodDelegate(Add);            Console.WriteLine(method(10,20));            Console.ReadKey();        }        private static int Add(int x, int y)        {            return x + y;        }

(2). Use of Action

Static void Main (string [] args) {Test <string> (Action, "Hello World! "); Test <int> (Action, 1000); Test <string> (p => {Console. writeLine ("{0}", p) ;}, "Hello World"); // use a Lambda expression to define the delegate Console. readKey ();} public static void Test <T> (Action <T> action, T p) {action (p);} private static void Action (string s) {Console. writeLine (s);} private static void Action (int s) {Console. writeLine (s );}

You can use the Action <T1, T2, T3, T4> delegate to pass methods in the form of parameters without explicitly declaring custom delegates. The encapsulated method must correspond to the method signature defined by the delegate. That is to say, the encapsulated method must have four parameters that are passed to it through values and cannot return values. (In C #, this method must return void.) generally, this method is used to execute an operation.

(3) Use of Func

        static void Main(string[] args)        {            Console.WriteLine(Test<int,int>(Fun,100,200));            Console.ReadKey();        }        public static int Test<T1, T2>(Func<T1, T2, int> func, T1 a, T2 b)        {            return func(a, b);        }        private static int Fun(int a, int b)        {            return a + b;        }

(4) use of predicate

Generic delegation: defines a set of conditions and determines whether the specified object meets these conditions. This delegate is used by several methods of the Array and List classes to search for elements in the collection.

        static void Main(string[] args)        {            Point[] points = { new Point(100, 200),             new Point(150, 250), new Point(250, 375),             new Point(275, 395), new Point(295, 450) };            Point first = Array.Find(points, ProductGT10);            Console.WriteLine("Found: X = {0}, Y = {1}", first.X, first.Y);            Console.ReadKey();        }        private static bool ProductGT10(Point p)        {            if (p.X * p.Y > 100000)            {                return true;            }            else            {                return false;            }        }

Use the Predicate delegate with the Array. Find method to search for the Array of the Point structure. If the product of the X and Y fields is greater than 100,000, the method ProductGT10 represented by this delegate returns true. The Find method calls this delegate for each element of the array and stops at the first vertex that meets the test conditions.

  3. Delegate clearing

(1) Declare the delegate method in the class and remove the delegate reference cyclically.

The method is as follows:

      public MethodDelegate OnDelegate;                        public void ClearDelegate()                {                         while (this.OnDelegate != null)             {                                 this.OnDelegate -= this.OnDelegate;              }                } 

(2) If the method for clearing the delegate is not stated in the class, we can use GetInvocationList to query the delegate reference and then remove it.

The method is as follows:

        public MethodDelegate OnDelegate; 
     static void Main(string[] args) { Program test = new Program(); if (test.OnDelegate != null) { System.Delegate[] dels = test.OnDelegate.GetInvocationList(); for (int i = 0; i < dels.Length; i++) { test.OnDelegate -= dels[i] as MethodDelegate; } } }

4. Delegation features

Delegation is similar to C ++ function pointers, but they are type-safe.
The delegate allows passing methods as parameters.
A delegate can be used to define a callback method.
The delegate can be linked together. For example, multiple methods can be called for an event.
The method does not have to match the delegate signature completely.

5.Summary:

Delegate has at least 0 parameters and up to 32 parameters. You can specify no return value or the return value type.

Func can accept 0 to 16 input parameters and must return values.

Action can accept 0 to 16 input parameters without returning values.

Predicate can only accept one input parameter. The returned value is of the bool type.

 

Http://www.fengfly.com/plus/view-209140-1.html

Http://www.cnblogs.com/foolishfox/archive/2010/09/16/1827964.html

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.