李白 hello!
李白 再见!
李白 想你了哈!
张三 想你了哈!
Play 没了
天田田发布了笑脸视频
键盘侠 说天田田 真年轻,一键三连 666~!
锅奇侠 说天田田 真漂亮,点赞噢~!
感谢您使用热水器,现在温度为10,
本次烧水时间为1分钟。(每分钟提高10摄氏度)
目前还没烧开!

感谢您使用热水器,现在温度为10,
本次烧水时间为10分钟。(每分钟提高10摄氏度)
叮叮叮,叮叮叮。。。
报警器提示水壶水温现在是100
显示器提示现在的水温为100

CarDealer,new car宝马
Michael:car 宝马 is new
CarDealer,new car奔驰
Michael:car 奔驰 is new
Nick:car 奔驰 is new
CarDealer,new car奥迪
Nick:car 奥迪 is new
msg:张三 发给 李四消息,内容是:Hello World!
妈妈 : 饭好了
爸爸 : 吃饭了。
孩子 : 打完这局再吃。
淘宝:发布衣服价格下降的公告,优衣库服装直降200元,限时抢购!
消费者:之前价格500,现在价格300,果断买了!
猫叫了一声

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using C = System.Console;
using System.Reflection;using noo;
using noo.First;
using System.Threading;namespace CShape测试
{internal class AttributeDefineMain{static List<Person> personList = new List<Person>(){new Person(){ Id=1,Name="小明",Age=20,Score=100},new Person(){ Id=2,Name="小王",Age=40,Score=80},new Person(){ Id=3,Name="小刘",Age=60,Score=60}};public delegate void SayHelloOlg(string name);public static void SayHello(string name){Console.WriteLine($"{name} hello!");}public static void SayBye(string name){Console.WriteLine($"{name} 再见!");}public static event SayHelloOlg SayHelloEvent;public static void Main(){//AttributeDefineExamle model = new AttributeDefineExamle();//Type type = model.GetType();//if (type.IsDefined(typeof(AttributeDefineDemo), true))//{//    var attribute = type.GetCustomAttribute<AttributeDefineDemo>();//    if (attribute.IsAge())//    {//        model.Show();//    }//}//MethodInfo method = model.GetType().GetMethod("Show");//if (method.IsDefined(typeof(AttributeDefineDemo), true))//{//    var attribute = method.GetCustomAttribute<AttributeDefineDemo>();//    if (attribute.IsAge())//    {//        model.Show();//    }//}//int num = MathAdd.Muti(12, 13);//MathAdd mathAdd = new MathAdd();//int num1 = mathAdd.Add(12, 12);IEnumerable var list = personList.Where((p) => p.Age < 50);var list = personList.Select(p => p.Name);//var list = personList.Select(p => new { id = p.Id, name = p.Name });//foreach (var tmp in list)//{ //    C.WriteLine(tmp);//}// 委托声明//委托的使用方法//委托的解释:将方法以变量的方式传递,并以方法的形式执行SayHelloOlg dlg = SayHello;dlg += SayBye;dlg += (string str) => Console.WriteLine($"{str} 想你了哈!"); dlg("李白");//事件,是被限制的委托SayHelloEvent += AttributeDefineMain_SayHelloEvent;if (SayHelloEvent != null){SayHelloEvent("张三");}//有利于 高内聚,低耦合// 事件的组成// 事件拥有者 事件成员  事件响应者 事件处理器 事件订阅//玩家 死亡==UI显示死亡// 玩家:事件拥有者  死亡:事件成员 UI:事件的响应者 显示死亡:事件处理器 桥梁:事件订阅 (只有订阅了的玩家才可以发生事件)/*Play{UI.WhenPlayDie();}UI{WhenPlayDie(){do some thing}}*/Player player = new Player();UI ui = new UI(player);if (player.hp <= 0)player.OnGUI();player.hp -= 200;if (player.hp <= 0)player.OnGUI();/*up主发动态, 粉丝响应*/Up up = new Up("天田田","笑脸视频");Fans fans1 = new Fans("键盘侠");Fans fans2 = new Fans("锅奇侠");up.publish += fans1.jianpanComment;up.publish += fans2.guoqixiaComment;up.OnPublish();//发布/*闹钟 响了 我 起床孩子 饿了 你 做饭隐含 订阅发生,响应模型事件拥有者 事件成员  事件响应者 事件处理器 事件订阅烧水 开了==报警器 报警*/Heater he1 = new Heater();     //第一次烧水(水没烧开,不会触发事件)he1.Temperature = 10;Alarm al1 = new Alarm();Display di1 = new Display();he1.DoMyAlarm += al1.MakeAlert;      //建立关联he1.DoMyDisplay += di1.ShowMsg;      //建立关联he1.BoilWater(1);Heater he2 = new Heater();     //第二次烧水(水烧开,触发显示与报警事件)he2.Temperature = 10;Alarm al2 = new Alarm();Display di2 = new Display();he2.DoMyAlarm += al2.MakeAlert;   //建立关联he2.DoMyDisplay += di2.ShowMsg;   //建立关联he2.BoilWater(10);CarDealer dealer = new CarDealer();Consumer michael = new Consumer("Michael");dealer.NewCardInfo += michael.NewCarIsHere;      //订阅事件dealer.NewCar("宝马");Consumer nick = new Consumer("Nick");dealer.NewCardInfo += nick.NewCarIsHere;         //订阅事件dealer.NewCar("奔驰");dealer.NewCardInfo -= michael.NewCarIsHere;      //取消订阅事件dealer.NewCar("奥迪");MailManager mm = new MailManager();Fax f = new Fax(mm);mm.SimulateNewMail("张三", "李四", "Hello World!");//实例化对象Mom mom = new Mom();Dad dad = new Dad();Child child = new Child();//将爸爸和孩子的Eat方法注册到妈妈的Eat事件//订阅妈妈开饭的消息mom.Eat += dad.Eat;mom.Eat += child.Eat;//调用妈妈的Cook事件mom.Cook();EventStandard.Show();Cat cat = new Cat();Mouse mouse = new Mouse(cat);People people = new People(cat);cat.Scream();/*事件: 能够发生的什么事情事件: 是类的成员事件发生的效果,就是对象的功能【通知能力】 就是通知*/Console.Write("Press any key to continue . . . ");C.ReadKey();}#region/*服装价格变动,触发淘宝发布活动和消费者购买衣服事件流*/public class EventStandard{public class Clothes{/// <summary>/// 服装编码/// </summary>public string Id { get; set; }/// <summary>/// 服装名称/// </summary>public string Name { get; set; }/// <summary>/// 服装价格/// </summary>private double _price;public double Price{get { return this._price; }set{PriceRiseHandler?.Invoke(this, new PriceEventArgs(){OldPrice = this._price,NewPrice = value});this._price = value;}}/// <summary>/// 服装价格变动事件/// </summary>public event EventHandler PriceRiseHandler;}/// <summary>/// 衣服价格事件参数 一般会为特定的事件去封装个参数类型/// </summary>public class PriceEventArgs : EventArgs{public double OldPrice { get; set; }public double NewPrice { get; set; }}public class TaoBao{/// <summary>/// 淘宝订户/// </summary>public void PublishPriceInfo(object sender, EventArgs e){Clothes clothes = (Clothes)sender;PriceEventArgs args = (PriceEventArgs)e;if (args.NewPrice < args.OldPrice)Console.WriteLine($"淘宝:发布衣服价格下降的公告,{clothes.Name}服装直降{args.OldPrice - args.NewPrice}元,限时抢购!");elseConsole.WriteLine("淘宝:价格悄悄上涨或价格未变化,啥也不做");}}public class Consumer{/// <summary>/// 消费者订户/// </summary>public void Buy(object sender, EventArgs e){Clothes clothes = (Clothes)sender;PriceEventArgs args = (PriceEventArgs)e;if (args.NewPrice < args.OldPrice)Console.WriteLine($"消费者:之前价格{args.OldPrice},现在价格{args.NewPrice},果断买了!");elseConsole.WriteLine($"消费者:等等看,降价了再说");}}public static void Show(){Clothes clothes = new Clothes(){Id = "12111-XK",Name = "优衣库",Price = 500};//订阅:把订户和发布者的事件关联起来clothes.PriceRiseHandler += new TaoBao().PublishPriceInfo;clothes.PriceRiseHandler += new Consumer().Buy;//价格变化,自动触发订户订阅的事件clothes.Price = 300;}}#endregion// 经典面试题,猫叫、老鼠跑了,主人醒来了public delegate void ScreamHandler();public class Cat{ public event ScreamHandler OnScream;public void Scream(){C.WriteLine("猫叫了一声");OnScream?.Invoke();}}public class Mouse{ public Mouse(Cat c){c.OnScream += () =>{C.WriteLine("老鼠跑了");};}}public class People{public People(Cat c){c.OnScream += () =>{C.WriteLine("主人醒来了");};}}#region/*我们用一个简单的例子,来说明一下这种消息传递的机制。有一家三口,妈妈负责做饭,爸爸和孩子负责吃。。。将这三个人,想象成三个类。妈妈有一个方法,叫做“做饭”。有一个事件,叫做“开饭”。做完饭后,调用开发事件,发布开饭消息。爸爸和孩子分别有一个方法,叫做“吃饭”。将爸爸和孩子的“吃饭”方法,注册到妈妈的“开饭”事件。也就是,订阅妈妈的开饭消息。让妈妈做完饭开饭时,发布吃饭消息时,告诉爸爸和孩子一声。*/public class Mom{//定义Eat事件,用于发布吃饭消息public event Action Eat;public void Cook(){Console.WriteLine("妈妈 : 饭好了");//饭好了,发布吃饭消息Eat?.Invoke();}}public class Dad{public void Eat(){//爸爸去吃饭Console.WriteLine("爸爸 : 吃饭了。");}}public class Child{public void Eat(){//熊孩子LOL呢,打完再吃Console.WriteLine("孩子 : 打完这局再吃。");}}#endregion#region/// <summary>/// 事件附加消息/// </summary>public class NewMailEventArgs : EventArgs{private readonly string m_from, m_to, m_subject;public NewMailEventArgs(string from, string to, string subject){m_from = from;m_to = to;m_subject = subject;}// 发件人public string From { get { return m_from; } }// 接收人public string To { get { return m_to; } }// 主题public string Subject { get { return m_subject; } }}public class MailManager{// 定义事件成员public event EventHandler<NewMailEventArgs> NewMail;// 定义负责引发事件的方法来通知已登记的对象protected virtual void OnNewMail(NewMailEventArgs e){// 将字段复制到一个临时变量,避免多线程情况中这个成员被移除EventHandler<NewMailEventArgs> temp = Volatile.Read(ref NewMail);// if (temp != null) temp(this, e);temp?.Invoke(this,e);}// 接受附加信息并调用引发事件的方法来通知所有登记的对象public void SimulateNewMail(string from, string to, string subject){NewMailEventArgs e = new NewMailEventArgs(from, to, subject);OnNewMail(e);}}public class Fax{public Fax(MailManager mm){// 构造委托实例,向事件登记回调方法mm.NewMail += FaxMsg;}/// <summary>/// 回调方法/// </summary>/// <param name="sender">表示MailManager对象,便于将信息传递给他</param>/// <param name="e">表示MailManager对象想传给我们的附加信息</param>private void FaxMsg(object sender, NewMailEventArgs e){Console.WriteLine("msg:{0} 发给 {1}消息,内容是:{2}", e.From, e.To, e.Subject);}/// <summary>/// 注销对事件的登记/// </summary>/// <param name="mm"></param>public void Unregister(MailManager mm){mm.NewMail -= FaxMsg;}}#endregion#region 测试事件1//EventArgs类public class CardInfoEventArgs : EventArgs{public string Car { get; private set; }public CardInfoEventArgs(string car){this.Car = car;}}//触发事件的类public class CarDealer{public event EventHandler<CardInfoEventArgs> NewCardInfo;public void NewCar(string car){Console.WriteLine("CarDealer,new car{0}", car);//在触发事件之前,需要检查委托NewCardInfo是否不为空。如果没有订阅处理程序,委托就是空if (NewCardInfo != null){NewCardInfo(this, new CardInfoEventArgs(car));}}}//处理事件的类public class Consumer{private string name;public Consumer(string name){this.name = name;}//处理事件的方法public void NewCarIsHere(object sender, CardInfoEventArgs e){Console.WriteLine("{0}:car {1} is new", name, e.Car);}}#endregion//public delegate void MyAlarm(int temperature);           //创建委托报警//public delegate void MyDispaly(int temperature);         //创建委托显示class Heater{// public event MyAlarm DoMyAlarm;        //建立事件报警// public event MyDispaly DoMyDisplay;     //建立事件显示public event EventHandler<My_EventArgs> DoMyAlarm;public event EventHandler<My_EventArgs> DoMyDisplay;private int temperature;    //温度public int Temperature{get { return temperature; }set{if ((temperature >= 0) && (temperature <= 100))temperature = value;elseConsole.WriteLine("温度有问题!显示出错!");}}public void BoilWater(int m)       //m 表示烧水时间,没分钟提高摄氏度{Console.WriteLine("感谢您使用热水器,现在温度为{0},\n本次烧水时间为{1}分钟。" +"(每分钟提高10摄氏度)", this.temperature, m);this.temperature = m * 10 + this.temperature;if (this.temperature >= 100)this.temperature = 100;if (this.temperature >= 95){if(DoMyAlarm!=null)DoMyAlarm(this, new My_EventArgs(this.temperature));if(DoMyDisplay!=null)DoMyDisplay(this, new My_EventArgs(this.temperature));Console.WriteLine("");}elseConsole.WriteLine("目前还没烧开!\n");}}class My_EventArgs : EventArgs{public  int temperature;public My_EventArgs(int temperature){this.temperature = temperature;}}class Alarm         //报警器类{           public void MakeAlert(object o,EventArgs eventargs){My_EventArgs e = (My_EventArgs)eventargs;Console.WriteLine("叮叮叮,叮叮叮。。。\n报警器提示水壶水温现在是{0}", e.temperature);}}class Display         //显示器类{public void ShowMsg(object o, EventArgs eventargs){My_EventArgs e = (My_EventArgs)eventargs;Console.WriteLine("显示器提示现在的水温为{0}", e.temperature);}}class MyEventArgs :EventArgs{public string name,content;}class Up{public event EventHandler publish;// 委托字段   event 必须持有,如果不持有,publish不是真正意义上的事件,会被强行调用。起安全作用//事件就是委托的限定器。限制所有的功能。//除了订阅 和取消订阅 string name;string content;//发布内容public Up(string name, string content) { this.name = name; this.content = content; }public void OnPublish(){C.WriteLine($"{name }发布了{content}");MyEventArgs args = new MyEventArgs();args.name = name;args.content = content;publish(name,args);}}class Fans{string name;string comment;public Fans(string name) { this.name = name;}internal void guoqixiaComment(object upName, EventArgs content){C.WriteLine($"{this.name} 说{upName} 真漂亮,点赞噢~!");}internal void jianpanComment(object upName, EventArgs content){C.WriteLine($"{this.name} 说{upName} 真年轻,一键三连 666~!"); }}public class Player{public delegate void ClickAction();public event ClickAction Death;public int hp;public Player(){hp = 100;}public void OnGUI(){Death();}}public class UI{private readonly Player Player;public UI(Player player){ Player = player;Player.Death += DeathHandler;}~UI(){Player.Death -= DeathHandler;}void DeathHandler(){C.WriteLine("Play 没了");}}private static void AttributeDefineMain_SayHelloEvent(string name){Console.WriteLine($"{name} 想你了哈!");}}class Person{public int Id, Age, Score;public string Name;public override string ToString(){return base.ToString() + " " + Id + "," + Name + "," + Age + "," + Score;}}
}

C# 事件相关的练习代码。相关推荐

  1. 函数、原生JS的事件相关(上)

    @关于函数和原生JS的一些事件相关知识点 函数的返回值 所有的函数都会有返回值,一般函数的返回值默认是undefined 函数内使用return来自定义返回值,但是注意return语句之后的代码全部都 ...

  2. HAPPE+ER软件:标准化事件相关电位ERP的预处理的pipeline

    摘要 事件相关电位(ERP)设计是一种用脑电图(EEG)评估神经认知功能的常用方法.然而,传统的ERP数据预处理方法是手动.主观.耗时的过程,许多自动化处理方法也很少有针对ERP分析有优化(特别是在发 ...

  3. 如何评价2022年数维杯国际赛C题【如何使用大脑结构诊断阿尔茨海默病】【D题:拉尼娜事件】思路模型代码全套资料+高清代码结果图+完整源程序+论文

    资料获取方式我放到下面了,欢迎小伙伴一起学习交流 2022数维杯国际赛C题:https://mbd.pub/o/bread/Y5yVlp1x2022年数维杯国际赛[D题:拉尼娜事件]思路模型代码全套资 ...

  4. JS事件相关知识点整理

    JS事件相关知识点整理 JS事件的驱动机制 常见JS事件 点击事件---onclick 焦点事件 获取焦点事件---onfocus 失去焦点事件----onblur 域内容改变事件---onchang ...

  5. 【radar】毫米波雷达相关开源项目代码汇总(工具箱、仿真、2D毫米波检测、融合、4D毫米波检测、分割、SLAM、跟踪)(6)

    [radar]毫米波雷达相关开源项目代码汇总(工具箱.仿真.2D毫米波检测.融合.4D毫米波检测.分割.SLAM.跟踪)(6) Toolbox pymmw https://github.com/m6c ...

  6. 关于事件相关电位SSVEP应用于视频游戏的研究

    点击上面"脑机接口社区"关注我们 更多技术干货第一时间送达 前面介绍过事件相关电位P300应用于视频游戏的研究: 关于事件相关电位P300应用于视频游戏的研究 今天主要介绍事件相关 ...

  7. 事件相关去同步 (ERD) 和事件相关同步化 (ERS)在脑电信号研究中的应用

    作者:周思捷,白红民,广州军区广州总医院神经外科 人脑具有电活动是Hans Berger于1924年首先检测到的,并将这种检测方法命名为脑电图(electroencephalo-graph,EEG). ...

  8. element-ui 框架的checkbox组件:点击事件 与 选中判断 - 代码篇

    vue + element-ui 框架的checkbox组件:点击事件 与 选中判断 代码如下: html部分 <!-- 全选 刷新 --> <div class="btn ...

  9. html5视频播放事件相关

    html5视频播放事件相关 使用: 监听视频播放结束 var myVideo = $("#videoPlayExecute"); // 监听视频播放结束 myVideo[0].ad ...

最新文章

  1. 数据结构--数组队列的实现
  2. AI独角兽面对BAT,挑战还是臣服?| 《财经》封面
  3. 入职阿里啦!java面试技巧之不要给自己挖坑实战干货
  4. 四则运算2.0版程序
  5. Qt实现UDP通信简例
  6. history.back(-1)和history.go(-1)的区别
  7. java模拟火车站买票的过程_Java常用代理
  8. Java XMPP负载测试工具
  9. Nginx----高级
  10. 戴尔融合“刀片”+双活存储助用户三网改造
  11. 新计算机主板不亮,电脑组装完毕之后点不亮怎么办 新电脑组装好开不了机的解决办法...
  12. 华为交换机eth口作用_华为交换机口如何绑定端口号
  13. java职业教育考试题_云课堂智慧职教java职业证书题库答案
  14. 服务器显示cpu温度高,高手教你巧解cpu温度过高问题
  15. 机器如何猜你所想?阿里小蜜预测平台揭秘
  16. 修改rpg maker mv的几种上限2020-05-25
  17. JavaScript-常见数组内置方法
  18. Linux Ubuntu常用软件
  19. 混合索引java代码,Elasticsearch 实现拼音,中文,首字母混合搜索
  20. 不羡鸳鸯不羡仙,一行代码调半天。SpringBoot集成任务调度,实现每天定时发送天气预报,随时做好“广冻人”的心理准备

热门文章

  1. 什么?都快过年了,你还没有买鞭炮
  2. 【时间之外】软件开发工作交接你会做吗?
  3. 高人气笔记本电脑推荐,购机必看
  4. vue动图加载图片不能正确显示的解决方法
  5. 慧编程,mbot自动巡线(流畅版)
  6. Android面试总结,终于有人把安卓程序员必学知识点全整理出来了,移动架构师成长路线
  7. [BOST] 你的大脑比你想象的更优秀
  8. 骨传导耳机音质好不好、音质最好的骨传导耳机推荐
  9. 淘宝退货业务 活动图
  10. 牵手碧桂园,天猫好房布下一盘房产交易大棋