Analysis of differences and linkages between delegates, events, Func, Action, predicate in C # through IL

Source: Internet
Author: User
Tags visual studio 2010

It's always been a bit confusing for events and delegates, and it's not going to work. Find a time, summed up a bit, feel a lot clearer.

Let's start with a personal understanding of the conclusion that:

delegate is a type in C # that is actually a class that holds a reference to a method.

There is no essential difference between the variable declared by delegate and the event declared by delegate, and the event is wrapped on the basis of the delegate declaration variable, The security is enhanced by the relationship between variables and attributes (you can see in IL code that each delegate declared event corresponds to a private delegate declared variable).

Action and Func: These two are actually the system-defined delegate, he has a lot of overloaded methods to facilitate the invocation of various application cases. He is in the System namespace, so it is globally visible.

First look at the meaning of icons in ildasm:

This figure from: http://www.php.cn/

Delegate creation steps:

1. Create a delegate with the delegate keyword, including the declaration return value and the parameter type
2, the use of the place to receive this delegation
3. Create an instance of this delegate and specify a return value and parameter type matching method passing past


I. Events and commissions



Create a new event Delegate test project: Eventdelegatetest

The specific code is as follows:

<span style= "FONT-SIZE:14PX;" ><span style= "FONT-SIZE:14PX;" >namespace eventdelegatetest{public    class TestClass    {public        delegate int delegateaction ();        public event delegateaction Onactionevent;        Public delegateaction danew;    }} </span></span>

After compiling the code, use the ILDASM.EXE that comes with Visual Studio 2010:



To open the DLL, you can see the following information:



You can see the following information:

1, Entrust public delegate int delegateaction ();

In IL is in the form of a class (Delegateaction)

. NET defines a delegate as a sealed class, derived from the base class System.MulticastDelegate, and inherits the three methods of the base class


2, public event delegateaction Onactionevent;

In IL, it not only corresponds to the event onactionevent but also corresponds to a field onactionevent;

Field Onactionevent is the same as the field danew generated by the public delegateaction danew.





Are present in the form of fields (field).

Double-click event Onactionevent to see the following information:




In IL, the event is encapsulated into a code snippet that contains a add_ prefix and a remove_ prefix.

The method of add_ prefix is actually implemented by calling the Delegate.combine () method, which makes up a multicast delegate; Remove_ is called the Delegate.remove () method to remove a delegate from a multicast delegate.

In other words: The event is actually a special multicast delegate

So what is the benefit of this encapsulation of events?

1, because delegate can support a lot of operations, such as we can write onxxxchanged + = Aaafunc, a function pointer attached to this delegate, but we can also simply rudely directly write onxxxchanged = Aaafunc, Let this delegate contain only this one function pointer. However, this creates a security problem: if we use onxxxchanged = Aaafunc, then we will overwrite the other function pointers that the delegate already owns, which is probably not the result that the programmer who defines onxxxchanged wants to see.

Small bet

Although an event cannot be directly =null a function, it cannot be directly


2. Another problem is onxxxchanged when this delegate should be triggered (that is, call the function pointer it contains). From an object-oriented perspective, XXX changes This fact (that is, the literal meaning of onxxxchaned) should be determined by the object that contains it. But we can actually call onxxxchanged from the external environment of this object, which creates both security and object-oriented intentions.

When it comes to the management of events and delegates, it is understood that the usual action and func, and what is the relationship between the Commission?


Ii. Action and Func


Action delegate: Encapsulates a method that has parameters (0 to 16 parameters ) and does not return a value.

The specific form is as follows: http://www.php.cn/(v=vs.110). aspx


Func<t, Tresult> delegate: Encapsulates a method that has parameters (0 to 16 parameters) and returns the type value specified by the TResult parameter.

The specific form is as follows: http://www.php.cn/(v=vs.110). aspx


So how is this action and func implemented?

1.Action (with Action<t1, t2> delegate: Encapsulates a method that has two parameters and does not return a value as an example)

From the source code published by Microsoft, you can see that the following implementation:


public action<bool,bool>  AC;

The above declaration is: the method has two parameters and does not return a value of the delegate.


The remainder is used in the same manner as the delegate variable.

2.Func (with func<t1, T2, tresult> delegate: Encapsulates a method that has two parameters and returns the type value specified by the TResult parameter as an example)
From the source code published by Microsoft, you can see that the following implementation:



Here, it can be seen that Func is similar to action, the only difference is that Func must specify the type of the return value, using the same way as the delegate we use the delegate variable, the Func or the action declaration variable directly using the corresponding parameter, = or + = Mount Function (method)

These two are actually the system-defined delegate, he has a lot of overloaded methods, convenient for various applications in the case of the call. He is in the System namespace, so it is globally visible.


Third, predicate


is a generic delegate that returns a bool type, predicate has only one parameter, and the return value is fixed to bool. Represents a method that defines a set of conditions and determines whether the specified object conforms to those conditions. This method is often used in lookups of collections (array and list<t>), such as arrays, which are used in the result set of a regular blend.

Official documents: Click to open link


Use the following demo:


using system;using system.collections.generic;using System.componentmodel;using system.data;using system.drawing;using system.linq;using System.Text;using System.windows.forms;namespace icontest{public partial class Form2:form {predicate<int> mypredicate        ;        int[] MyNum = new Int[8] {12, 33, 89, 21, 15, 29, 40, 52};        Public int[] Myresult;            Public Form2 () {InitializeComponent ();                    Mypredicate = delegate (int curnum) {if (curnum% 2 = = 0) {                return true;                } else {return false;        }            }; private void Form2_load (object sender, EventArgs e) {myresult = Array.findall (MyNum, Mypredica        TE); }              }}

The above example illustrates the use of predicate, the FindAll method, parameter 2 is a predicate, in the specific execution, each element of the array will execute the specified method, if the requirements return true, and will be stored in the result set, non-conforming is rejected, The final returned collection, which is the desired collection after the result is judged.
Array.findall generic method: Click the Open link


The result of the above code execution is:


So what does predicate<t> have to do with entrusting?


From the Microsoft source, it can be seen that predicate<t> is a generic delegate that returns bool type, which is inherently different from Func, Action, event, and delegate variables.




The above is through IL Analysis of C # delegate, event, Func, Action, predicate between the difference and contact content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!


  • 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.