首页 > 代码库 > 猫与老鼠的故事(委托)
猫与老鼠的故事(委托)
public delegate void catMiaoHanler(Cat cat); public class Cat { public catMiaoHanler thisHanler; public string Name { get; set; } public Cat() { } public void Miao() { Console.WriteLine("miao miao miao "); thisHanler(this); } } class Mouse { public string Name { get; set; } public int Level { get; set; } public Mouse(Cat listenCat) { listenCat.thisHanler += (cat) => { if (Level > 10) Console.WriteLine(cat.Name + "is coming!!!" + this.Name + " go go go "); else Console.WriteLine(cat.Name + "is coming!!!" + this.Name + " is dead!"); }; } } class Program { static void Main(string[] args) { //Cat cat = new Cat(new List<Mouse> { new Mouse { Name = "tom", Level = 1 }, new Mouse { Name = "jack", Level = 2 } }); Cat cat = new Cat { Name = "Tim" }; Mouse m1 = new Mouse(cat) { Name = "tom", Level = 9 }; Mouse m2 = new Mouse(cat) { Name = "tom2", Level = 19 }; cat.Miao(); Console.ReadLine(); } }
miao miao miao
Timis coming!!!tom is dead!
Timis coming!!!tom2 go go go
猫与老鼠的故事(委托)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。