Introduction to C # Delegates (delegate, Action, Func, predicate)

Source: Internet
Author: User

From:http://www.cnblogs.com/akwwl/p/3232679.html

A delegate is a class that defines the type of the method so that the method can be passed as a parameter to another method. An event is a special kind of delegate.

1. Declaration of Delegation

(1). Delegate

Delegate the kind of statement we used to use

Delegate at least 0 parameters, up to 32 parameters, can have no return value, or you can specify a return value type.

Example: public delegate int methodtdelegate (int x, int y), two arguments, and int type.

(2). Action

Action is a generic delegate with no return value.

The Action represents a delegate without parameters and no return value

Action<int,string> represents a delegate with an incoming parameter int,string no return value

Action<int,string,bool> represents a delegate with an incoming parameter Int,string,bool no return value

Action<int,int,int,int> represents a delegate that has passed in 4 int parameters, no return value

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

Cases:

        public void test<t> (action<t> action,t p)        {            Action (p);        }

(3). Func

Func is a generic delegate with a return value

Func<int> represents no parameter and returns a delegate with a value of int

Func<object,string,int> indicates that an incoming parameter is an object, and a string returns a delegate with a value of int

Func<object,string,int> indicates that an incoming parameter is an object, and a string returns a delegate with a value of int

Func<t1,t2,,t3,int> represents a delegate with an incoming parameter of T1,T2,,T3 (generic) that returns a value of int

Func at least 0 parameters, up to 16 parameters, are returned based on the return value generic. Must have a return value, not void

Cases:

        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 a bool type

Predicate<int> represents a delegate with an incoming parameter of int returning BOOL

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

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

2. Use of the delegate

(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, +);            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 ACTION<T1, T2, T3, and t4> delegates to pass methods as arguments without explicitly declaring a custom delegate. The encapsulated method must correspond to the method signature defined by this delegate. That is, the encapsulated method must have four parameters that are passed to it by value and cannot return a value. (in C #, the method must return void) Typically, this method is used to perform 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 delegate: Represents a method that defines a set of conditions and determines whether the specified object conforms to those 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 (+), new Point (             250, 375),             new Point (275, 395), New Point (295,)};            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;            }        }

Searches an array of point structures using the predicate delegate with the Array.find method. 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, stopping at the first point that meets the test condition.

3. Empty the delegate

(1). Declare the empty delegate method in the class, and loop to remove the delegate reference in turn.

Here's how:

  Public methoddelegate ondelegate;                        public void Cleardelegate ()                {while                         (this. Ondelegate = null)             {this                                 . Ondelegate-= this. ondelegate;              }                

(2). If the method of emptying the delegate is not declared in the class, we can use Getinvocationlist to query the delegate reference and then remove it.

Here's how:

        
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. Characteristics of the Commission

Delegates are similar to C + + function pointers, but they are type-safe.
A delegate allows a method to be passed as a parameter.
Delegates can be used to define callback methods.
Delegates can be chained together; For example, multiple methods can be called on an event.
method does not have to match the delegate signature exactly.

5. Summary:

Delegate at least 0 parameters, up to 32 parameters, can have no return value, or you can specify a return value type

Func can accept 0 to 16 incoming parameters and must have a return value

Action can accept 0 to 16 incoming parameters, no return value

predicate can only accept one incoming parameter, the return value is type bool

Detailed reference: http://www.fengfly.com/plus/view-209140-1.html

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

Introduction to C # Delegates (delegate, Action, Func, predicate)

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.