First we have to figure out what is a delegate? Trust is not unfamiliar to the Commission, the delegation is actually a definition of the type of method signature; There is a detailed description of the delegation, you can refer to the MSDN Introduction, the link is: http://msdn.microsoft.com/zh-cn/library/vstudio/ Ms173171.aspx. Here I do not make a specific introduction;
This article I mainly want to tell you what the internal structure of the entrusted, we first through a simple demo to review the Commission:
Copy Code code as follows:
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;
Namespace _01delegate
{
The signature of the constraint's pointing method, which is a strongly typed pointer
public delegate int Adddele (int a, int b);
Class Program
{
static void Main (string[] args)
{
Define a delegate variable, and note that when you point to the first method, you must use the New keyword followed by + =
Adddele delstatic = new Adddele (ADD);
Using delegates: A delegate of a static method
Console.WriteLine (Delstatic (3, 4));
Delegate of instance method
Program P = new program ();
Adddele delinstance = new Adddele (p.addinstance);
Output: 9
Console.WriteLine (Delinstance (4, 5));
Console.readkey ();
}
static method
static int Add (int a, int b)
{
return a + B;
}
Instance method
public int addinstance (int a, int b)
{
return a + B;
}
}
}
The above code, respectively, using the delegate to the static method and instance method calls, if this code seems to be very difficult, I recommend the link in front of me to properly consolidate the relevant content of the delegate.
Starting point: The internal construction of a delegate
The internal Commission can be divided into three parts: _target,_methodptr and Entrust chain respectively; (Take the demo above as an example)
_target: As the name implies, is the objective function of the delegate, if it is a static method, _target is null; if it is an instance method, _target is pointing to the current instance, and the _target value of the delinstance in the example above is P ( Examples of program);
_methodptr: A method pointer that points to the address of the method in memory;
Entrust chain: Through + + operation of the formation of the Commission chain, in fact, the point is a method;
I simply drew a picture to describe the internal construction of the delegate: (as follows)
These are some of my understanding, if there are wrong places to welcome everyone to point out and discuss each other to learn, I hope this article for you to understand commissioned help, but also in order to improve themselves and record their own little learning accumulation.