A delegate is a class.
namespace ConsoleApplication1
{
internal delegate void MyDelegate(int val);
class Program
{
static void Main(string[] args)
{
}
}
}
Use reflector to view the delegate il code:
○ Delegate is indeed a class
○ Delegate constructor receiver method and class instance
○ It is also a multicast delegate and can be assigned a value using ++ =.
○ Delegate internal use of the invoke Method for triggering
○ Begininvoke and endinvoke methods are used in multithreading scenarios.
Next, we will experience how to use the delegate and what the delegate's method and target attributes represent.
namespace ConsoleApplication1
{
internal delegate void MyDelegate(int val);
class Program
{
static void Main(string[] args)
{
// Delegate and static methods
MyDelegate d = new MyDelegate(M1);
d(10);
Console.WriteLine(d.Method);
if (d.Target == null)
{
Console. writeline ("The current delegate calls static methods without class instances ");
}
else
{
Console. writeline ("The current delegate calls an instance method, and the class instance is:" + D. Target );
}
Console.WriteLine("-------------------");
// Delegate and instance methods
Program p = new Program();
d = p.M2;
d.Invoke(10);
Console.WriteLine(d.Method);
if (d.Target == null)
{
Console. writeline ("The current delegate calls static methods without class instances ");
}
else
{
Console. writeline ("The current delegate calls an instance method, and the class instance is:" + D. Target );
}
}
static void M1(int val)
{
Console. writeline ("I Am a static method, output" + val );
}
void M2(int val)
{
Console. writeline ("I am an instance method, output" + val );
}
}
}
○ Create a delegate: Use the Delegate constructor, new mydelegate (M1), or D = P. m2, which is a method of writing "syntactic sugar", also calls the Delegate constructor internally.
○ Delegate and static methods: You can pass the static method to the Delegate constructor as long as the parameter list and return type are the same.
○ Delegate and instance methods: You can pass the instance method to the Delegate constructor as long as the parameter list and return type are the same.
○ Delegated call: for example, D. invoke (10), called through the entrusted instance method invoke; like D (10), this is a "syntax sugar" method, which also calls the instance method invoke internally.
○ Target attribute: indicates the name of the class instance to which the instance method belongs. If it is a static method, target is null.
○ Method attribute: The method represented by the delegate, which may be a static method or an instance method.
Delegate, Lambda expression, event series 01, Delegate, basic delegate usage, delegate method and Target attribute