Day 8 of advanced learning

Catalog

1. Define event 1

Role:
Event Publisher: publish event (the object that triggered the event)
Event subscriber: accept the event and handle it accordingly (capture and handle the event)

Define event: access modifier event delegate type event name
1. The modifier is generally public and visible to other classes
2. The delegation type can be user-defined or predefined EventHandler

 int main()
    {   friend f1 = new friend ();
	    friend f2 = new friend ();
	    bridge.myevent +=f1.thing;
	    bridge.myevent +=f2.thing;   //Subscription events
        bridge.myevent -=f2.thing;   //Remove events   
        bridge.sendthing ();         //Publishing events. Methods that call a delegation chain through a delegation chain call events indirectly through public methods
    }                                //Event can't call bridge.myevent() directly outside the class. It will report an error!
 class  bridge
 {      public delegate  void  mydele();
	    public static event mydele  myevent;  
	    public static void  sendthing()  {  myevent();  }    //public Method	
 }
 class friend
 {      public  void thing()  { Console.WriteLine ("wo zhi dao le !");  }
 }

1. Define events2

Prototype: public delegate void EventHandler (object sender, EventArgs e);
You can use the delegation type EventHandler provided by the system

 public event EventHandler myevent;         //bridge
 public  void  sendthing(string time,string place)
 {       EventArgs e = new EventArgs(time,place);
	     myevent (this,e);                                      //Who sent this
 }
 public class Myeventargs :EventArgs       //Extend EventArgs to pass parameters
 {
	     protected  string time;
	     protected  string place;
	     public Myeventargs(string time,string place)
	     {   this.time = time;
	          this.place = place;
	     }
 }
 public void thing(object sender,EventArgs e)   //friend
 {
	      Console.WriteLine ("{0}Received{1}Notice.,time{2}place{3} ", 
          name,((bridge)sender).name,((Myeventargs)e).time,((Myeventargs)e).place);
 }                                                                 
 int main()
 {
          bridge b = new bridge ("xin", 22);       //main
          friend f1 = new friend ("a", 21);
          b.myevent += f1.thing;
	      b.sendthing ("2017", "beijing");
   }

Posted by Volatile on Fri, 29 Nov 2019 23:10:24 -0800