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

本文提供了一个简单而完整的C#事件模型实例,通过Test类的DoTest方法触发onTest事件,利用testEventArgs参数控制输出行为,展示了委托与事件的基本用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

using System; namespace ConsoleApplication3 { class Program { //一个较为完整的委托-事件 模型应用 //by jinjazz //http://blog.youkuaiyun.com/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; } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值