C#练习委托、事件、事件处理
控制台应用程序效果:
代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MyEventTest { class Program { /// <summary> /// 第一步 新建委托需要的带参数的类,属于事件的参数的子类 /// </summary> public class MyClassEventArgs : EventArgs { private string name; public string Name { get { return name; } set { name = value; } } private int age; public int Age { get { return age; } set { age = value; } } } /// <summary> /// //第二步 新建一个带参数的委托 /// </summary> /// <param name="sender">触发源</param> /// <param name="mc">参数</param> public delegate void MyDelegate(object sender,MyClassEventArgs mc); /// <summary> /// 第三步 新建一个会触发事件的类 /// </summary> public class Custom { /// <summary> /// 第四步 新建一个委托发生时触发的事件 /// </summary> public event MyDelegate Shout; private string name; public string Name { get { return name; } set { name = value; } } private int age; public int Age { get { return age; } set { age = value; } } public Custom() { } public Custom(string n, int a) { name = n; age = a; } public void Buy() { Console.WriteLine("{0}:我要来买东西!",this.name); //第五步 在方法中关联事件 MyClassEventArgs mcea = new MyClassEventArgs(); mcea.Name = name; mcea.Age = age; if (Shout != null) { Shout(this,mcea); } } } /// <summary> /// 第六步 新建一个事件发生后要执行的类 /// </summary> public class Reporter { public void Notify(object sender, MyClassEventArgs mcea) { Console.WriteLine("老板:小白快去接客了,客户名字叫{0},年龄{1}岁",mcea.Name,mcea.Age); } } /// <summary> /// 第七步 做一种触发事件的情况,并把事件和事件的处理关联起来 /// </summary> /// <param name="args"></param> static void Main(string[] args) { Custom c1 = new Custom("大美女",18); Reporter r1 = new Reporter(); c1.Shout +=new MyDelegate(r1.Notify); c1.Buy(); } } }
文章对您有帮助,开心可以打赏我,金额随意,欢迎来赏!
需要电子方面开发板/传感器/模块等硬件可以到我的淘宝店逛逛