您的位置:首页 > 编程语言 > C#

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

2010-07-29 10:34 931 查看
这里设计了一个较为完整且简单的事件模型,帮助初学者了解c#的事件基本概念和逻辑。

view plaincopy to clipboardprint?
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;

}

}

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/jinjazz/archive/2009/02/17/3902863.aspx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: