1. Declare a delegate class
Public delegate SomethingChangedHandler (object sender, EventArgs e );
2. Declare an event bound to the delegate public event SomethingChangedHandler Changed in your class;
3. trigger this event in the corresponding method
Public void ChangeSomething ()
{
Changed (this, new EventArgs); // triggers the event
}
4. subscribe to events from callers
Your class's instance. Changed + = new SomethingChangedHandler (your method name );
5. cancel subscription
The object that subscribes to this event. Changed-= new SomethingChangedHandler (your method name );
Note: because events in c # are implemented by delegation, the delegation cannot be inherited, therefore, the event can only be defined by the event name in the class it defines (the parameter of the event Delegate ...). If an event needs to be triggered in a derived class, you can define a method to trigger the event in the base class SendSomeEvent (). In the derived class, override the method and call base. SendSomeEvent ();
See the following example:
Namespace ConsoleApplication3
{
Class press // define press class
{
Public delegate void publication (); // proxy required to declare an event
Public event published; // event statement
Public void release () // Method for triggering an event
{
Console. WriteLine ("publication ");
Published ();
}
}
Class subscriber // define the subscriber class
{
Public void subscription ()
{
Console. WriteLine ("subscriber has subscribed ");
}
}
Class Program
{
Static void Main (string [] args)
{
Press a press = new Press ();
Subscriber Zhang San = new subscriber ();
A publishing house. Published + = new publishing house. Published (Zhang San. subscribe); // subscribe to the event publisher for a meta event
Publishing House A. Release (); // trigger the event
}
}
}
Using System;
Public class Publisher // press www.2cto.com
{
Public delegate void Publish (string name); // declare the proxy required for the event
Public event Publish OnPublish; // event Declaration
Public void issue (string _ name) // Method for triggering an event
{
If (OnPublish! = Null)
{
Console. WriteLine ("publication ");
OnPublish (_ name );
}
}
}
Class Subscriber // Subscriber
{
Public void Receive (string str) // defines the event handler
{
Console. WriteLine ("subscriber" + str + "has received the publication! ");
}
}
Class story
{
Static void Main ()
{
Publisher Pub = new Publisher ();
Subscriber zs = new Subscriber ();
Pub. OnPublish + = new Publisher. Publish (zs. Receive );
Pub. issue ("James"); // trigger the event
}
}
From the snow that night