When I first learned that C # Is a contact with an event, I was thinking about how it works until I had a deeper understanding of the event through in-depth contact with the delegate. This is a back-to-function, in. NET Framework is widely used, such as form status changes, menu options, and so on. Have you ever thought about how it is implemented? We need to talk about delegation.
The delegate is something similar to the function pointer in C, but C # provides a more secure type mechanism for the delegate.
The following describes how to create and use a delegate statement:
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Namespace MyDelegate
{
Class Program
{
Public delegate void FunBock (int value );
Static void Main (string []
Args)
{
Program
P = new Program ();
StaticDelegate ();
InstanceDelegate (p );
ChainDelete (p );
}
Public static void counter (int
From, int tow, FunBock
Fb)
{
For
(Int I = from; I <= tow; I ++)
{
If (fb! = Null)
Fb (I );
Else
Return;
}
}
// Proxy static method
Public static void
StaticDelegate ()
{
Console. WriteLine ("------------- proxy static function ----------------");
Program. counter (0, 1, null );
Program. counter (0,
1, new FunBock (Program. StaticFunction ));
Console. WriteLine ();
}
// Proxy instance method
Public static void
InstanceDelegate (Program p)
{
Console. WriteLine ("------------ proxy instance method ----------------");
Program. counter (0,
1, null );
Program. counter (0,
1, new FunBock (p. ObjectFunction
));
Console. WriteLine ();
}
// Proxy serial Function
Public static void
ChainDelete (Program p)
{
Console. WriteLine ("------------ proxy serial function ----------------");
FunBock
Fb1 = null;
Fb1 = (FunBock) Delegate. Combine (fb1, new
FunBock (p. ObjectFunction ));
Fb1 = (FunBock) Delegate. Combine (fb1, new
FunBock (Program. StaticFunction ));
Program. counter (0,
1, fb1 );
Console. WriteLine ();
}
Public void ObjectFunction (int
Value)
{
Console. WriteLine ("ObjectFunction method value:" + value );
}
Private
Static void
StaticFunction (int value)
{
Console. WriteLine ("StaticFunction method value:" + value );
}
}
}
Resolution: The delegate statement specifies the signature of a delegate function. In this example, an int parameter is used without a delegate of the return type. This declares that all functions of an int parameter without a return type are directed to the value, similar to the concepts of classes and instance objects, FunBock class, all methods that meet the constraints can be considered as instances of this class!
The chain proxy implemented by chainDelete will be explained in detail in the delegation chain!