C#事件和委托的基础知识模型

这里设计了一个较为完整且简单的事件模型,帮助初学者了解c#的事件基本概念和逻辑。

 

 using System; namespace ConsoleApplication3 { class Program { //一个较为完整的委托-事件 模型应用 //by jinjazz //http://blog.csdn.net/jinjazz //模型表达 //Test对象执行DoTest方法,回调onTest事件,通过参数控制输出 static void Main(string[] args) { Test t1 = new Test(); t1.Name = "t1"; t1.onTest += new Test.dTest(t_onTest); Test t2 = new Test(); t2.Name = "t2"; t2.onTest += new Test.dTest(t_onTest); t1.DoTest("aaaa"); t2.DoTest("bbbb"); Console.Read(); } static void t_onTest(object sender, Test.testEventArgs args) { Test t = sender as Test; if(t.Name=="t1") args.Cancled = true; } } class Test { //委托参数 public class testEventArgs { public bool Cancled=false; } //委托 public delegate void dTest(object sender, testEventArgs args); //事件 public event dTest onTest; //函数 public void DoTest(string s) { if (this.onTest != null) { //参数判断 testEventArgs arg = new testEventArgs(); this.onTest(this, arg); if (arg.Cancled == true) { return; } } Console.WriteLine(s); } //成员变量 或 属性 public string Name = string.Empty; } } 

你可能感兴趣的:(object,String,C#,null,Class)