最重要的事件法则:有五个要素
事件1的写法
1 class Weituo 2 { 3 static void Main(string[] args) 4 { 5 Timer timer = new Timer();//事件拥有者 6 timer.Interval = 800.4; 7 timer.Elapsed += Boy.Action;//事件(触发)Elapsed 和事件订阅+= 8 timer.Start(); 9 10 ConsoleColor c=ConsoleColor.Red; 11 12 Console.ReadKey(); 13 } 14 } 15 16 class Boy//事件响应者Boy 17 { 18 internal static void Action(object sender, ElapsedEventArgs e)//事件处理器 19 { 20 Random rnd = new Random(); 21 int i=rnd.Next(1,24); 22 23 24 Console.WriteLine($"我跳!!!获得了{i}个金币"); 25 } 26 }
事件二(自己调用自己)字段变化
1 class Weituo 2 { 3 static void Main(string[] args) 4 { 5 Form form1 = new Form();//事件拥有者 6 Controller con1=new Controller(form1);//事件响应者 7 8 form1.ShowDialog(); 9 Console.ReadKey(); 10 11 } 12 } 13 14 15 class Controller 16 { 17 private Form form; 18 public Controller(Form form) 19 { 20 if (form !=null) 21 { 22 this.form = form; 23 this.form.Click += this.formClicked;//事件Ckick 和事件订阅+= 24 } 25 } 26 27 private void formClicked(object sender, EventArgs e)//事件的处理器 28 { 29 this.form.Text = DateTime.Now.ToString(); 30 } 31 }
第三种:自己触发自己
1 class Weituo 2 { 3 static void Main(string[] args) 4 { 5 MyForm form=new MyForm();//事件拥有者 响应者 6 form.Click += form.FormClicked;//事件触发器form.Click 和+=订阅符号 7 } 8 } 9 10 class MyForm : Form//事件响应者(是自己) 11 { 12 internal void FormClicked(object sender, EventArgs e)//事件处理器 13 { 14 this.Text = DateTime.Now.ToString(); 15 } 16 }
第四种:Form触发自己的
1 class Weituo 2 { 3 static void Main(string[] args) 4 { 5 MyForm1 myform=new MyForm1(); 6 myform.ShowDialog(); 7 } 8 } 9 10 11 class MyForm1 : Form 12 { 13 private Button button1; 14 private TextBox textBox1; 15 public MyForm1() 16 { 17 this.button1 = new Button(); 18 this.textBox1 = new TextBox(); 19 this.Controls.Add(this.button1); 20 this.Controls.Add(this.textBox1); 21 this.button1.Click += this.ButtonClick; 22 this.button1.Text= "Click"; 23 this.button1.Top = 50; 24 } 25 26 private void ButtonClick(object sender, EventArgs e) 27 { 28 Console.WriteLine(sender.ToString()); 29 } 30 }
委托和事件方法