李白 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
personList = new List() - {
- 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
(); - // if (attribute.IsAge())
- // {
- // model.Show();
- // }
- //}
-
- //MethodInfo method = model.GetType().GetMethod("Show");
- //if (method.IsDefined(typeof(AttributeDefineDemo), true))
- //{
- // var attribute = method.GetCustomAttribute
(); - // 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
- {
-
- ///
- /// 服装编码
- ///
- public string Id { get; set; }
-
- ///
- /// 服装名称
- ///
- public string Name { get; set; }
-
- ///
- /// 服装价格
- ///
- private double _price;
-
- public double Price
- {
- get { return this._price; }
- set
- {
- PriceRiseHandler?.Invoke(this, new PriceEventArgs()
- {
- OldPrice = this._price,
- NewPrice = value
- });
- this._price = value;
- }
- }
-
- ///
- /// 服装价格变动事件
- ///
- public event EventHandler PriceRiseHandler;
-
- }
-
- ///
- /// 衣服价格事件参数 一般会为特定的事件去封装个参数类型
- ///
- public class PriceEventArgs : EventArgs
- {
- public double OldPrice { get; set; }
- public double NewPrice { get; set; }
- }
-
- public class TaoBao
- {
- ///
- /// 淘宝订户
- ///
- 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}元,限时抢购!");
- else
- Console.WriteLine("淘宝:价格悄悄上涨或价格未变化,啥也不做");
- }
-
- }
-
- public class Consumer
- {
- ///
- /// 消费者订户
- ///
- 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},果断买了!");
- else
- Console.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
-
- ///
- /// 事件附加消息
- ///
- 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
NewMail; -
- // 定义负责引发事件的方法来通知已登记的对象
- protected virtual void OnNewMail(NewMailEventArgs e)
- {
- // 将字段复制到一个临时变量,避免多线程情况中这个成员被移除
- EventHandler
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;
- }
- ///
- /// 回调方法
- ///
- /// 表示MailManager对象,便于将信息传递给他
- /// 表示MailManager对象想传给我们的附加信息
- private void FaxMsg(object sender, NewMailEventArgs e)
- {
- Console.WriteLine("msg:{0} 发给 {1}消息,内容是:{2}", e.From, e.To, e.Subject);
- }
-
- ///
- /// 注销对事件的登记
- ///
- ///
- 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
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
DoMyAlarm; - public event EventHandler
DoMyDisplay; -
- private int temperature; //温度
- public int Temperature
- {
- get { return temperature; }
- set
- {
- if ((temperature >= 0) && (temperature <= 100))
- temperature = value;
- else
- Console.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("");
- }
- else
- Console.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;
- }
-
- }
- }