Agent delegate:
An object reference points to an object of a particular type.
The agent points to a method of a particular type.
Agent Four steps:
- Define custom proxy classes: public delegate void First (int i);
- Instantiate proxy class: first mydelegate = null;
- Example Add Method: MyDelegate + = new First (show);
- Method invocation via Instance object: MyDelegate (666);
Class Program
{
Defining Frist Proxies
public delegate void First (int i);
Main function, main entry
static void Main (string[] args)
{
To create a first type reference
First mydelegate = null;
To create a proxy reference to the Show method
MyDelegate + = new First (show);
Calling the Show method through proxy references
MyDelegate (666);
Console.readkey ();
}
Show method
public static void Show (int i)
{
Console.WriteLine (i.ToString ());
}
}
- The proxy definition is outside the method, including outside the class.
- The multiple proxy return type is void.
- Keyword delegate.
- Proxies can be passed to the inside of the method with parameters.
Such as:
Class Program
{
Defining Frist Proxies
public delegate void First (int i);
Main function, main entry
static void Main (string[] args)
{
To create a first type reference
First mydelegate = null;
To create a proxy reference to the Show method
MyDelegate + = new First (show);
Calling the Show method through proxy references
Diao (666, MyDelegate);
Console.readkey ();
}
Show method
public static void Show (int i)
{
Console.WriteLine (i.ToString ());
}
//
public static void Diao (int i,first dele)
{
Dele (i);
}
}
Events Event:
Defining Eventdelegate Proxies
public delegate void Eventdelegate ();
Class Program
{
Main function, main entry
static void Main (string[] args)
{
Instantiate Clocktimer
Clocktimer Clocktimer = new Clocktimer ();
Adding Onclocktimer methods in MyEvent
Clocktimer.myevent + = new Eventdelegate (Onclocktimer);
Show method for executing Clicktimer objects
Clocktimer.show ();
Console.ReadLine ();
}
Acceptance method
public static void Onclocktimer ()
{
Console.WriteLine ("Received clock event");
}
}
Event Generation Class
public class Clocktimer
{
Defining Events (Event)
public event Eventdelegate MyEvent;
Generating Event methods
public void Show ()
{
for (int i=0;i<1000;i++)
{
Generate events
MyEvent ();
Sleep 1 seconds
Thread.Sleep (+);//system.threading;
}
}
}
- First define the proxy (in-class or out-of-class definition).
Use the delegate keyword
- Define trigger events (defined according to the scope of the agent). If the proxy is defined inside the program class, the trigger event is written inside the program class.
Use the event keyword.
- Defines the method that handles triggering events.
Masters, above is my understanding of event and delegate. If there is something wrong, please help me to point out. Thank you very much!
Trivia (vii): Agents & Events