• 软件测试技术
  • 软件测试博客
  • 软件测试视频
  • 开源软件测试技术
  • 软件测试论坛
  • 软件测试沙龙
  • 软件测试资料下载
  • 软件测试杂志
  • 软件测试人才招聘
    暂时没有公告

字号: | 推荐给好友 上一篇 | 下一篇

一个关于代理和事件的例子

发布: 2007-7-01 20:40 | 作者: admin | 来源: | 查看: 32次 | 进入软件测试论坛讨论

领测软件测试网

前言

    这是在学习C#的代理和事件时写的一个例子,供大家参考。

正文

    代理和事件,我们在编程过程中也许会经常用到,尤其是编写windows应用程序时。在C和C++里我们都知道有函数指针的概念,在.Net中,函数指针则是以代理的形式出现的,代理比函数指针更安全。在.Net中,事件的实现就是以代理为基础的。

    下面我们来做个小例子,看一看代理和事件的实现过程。这个例子是这样的,当你点击按钮的时候,如果当前时间的秒小于30,就会提示“Wasn@#t the right time.”,否则就显示当前时间。

    首先定义代理和事件:

public delegate void ActionEventHandler( object sender, ActionCancelEventArgs ev );
public static event ActionEventHandler Action;

    然后定义一个类实现提示信息:

public class ActionCancelEventArgs:CancelEventArgs
 {
  string _msg = "";
  public ActionCancelEventArgs():base(){}
  public ActionCancelEventArgs(bool cancel):base(cancel){}
  public ActionCancelEventArgs(bool cancel,string message):base(cancel)
  {
   _msg = message;
  }
  public string message
  {
   set { _msg = value; }
   get { return _msg; }
  }
 }

    在点击按钮时的代码:

private void btnRaise_Click(object sender, System.EventArgs e)
  {
   BusEntity _busEntity = new BusEntity ();
   ActionCancelEventArgs cancelEvent = new ActionCancelEventArgs ();
   OnAction( this, cancelEvent );
   if( cancelEvent.Cancel )
    lblInfo.Text = cancelEvent.message ;
   else
    lblInfo.Text = _busEntity.TimeString ;
  }

    点击按钮发布事件的代码:

protected void OnAction( object sender, ActionCancelEventArgs ev )
  {
   if( Action != null )
    Action( sender, ev );
  }

    现在,事件发布了,要对事件进行处理,我们定义一个类:

public class BusEntity
 {
  string _time = "";
  public BusEntity()
  {
   Form1.Action += new Form1.ActionEventHandler(Form1_Action);
  }

  private void Form1_Action( object sender, ActionCancelEventArgs ev )
  {
   ev.Cancel = !DoActions();
   if(ev.Cancel )
    ev.message = "Wasn@#t the right time.";
  }
  private bool DoActions()
  {
   bool retVal = false;
   DateTime tm = DateTime.Now;
   if(tm.Second < 30)
   {
    _time = "The time is " + DateTime.Now.ToLongTimeString ();
    retVal = true;
   }
   else
    _time = "";
   return retVal;
  }
  public string TimeString
  {
   get { return _time; }
  }
 }

    我们可以看出,当当前时间的秒小于30时,就发布事件,显示信息,大于30时,就会取消事件,显示当前信息。

附:

    具体请看代码,错误之处欢迎指正。


延伸阅读

文章来源于领测软件测试网 https://www.ltesting.net/


关于领测软件测试网 | 领测软件测试网合作伙伴 | 广告服务 | 投稿指南 | 联系我们 | 网站地图 | 友情链接
版权所有(C) 2003-2010 TestAge(领测软件测试网)|领测国际科技(北京)有限公司|软件测试工程师培训网 All Rights Reserved
北京市海淀区中关村南大街9号北京理工科技大厦1402室 京ICP备2023014753号-2
技术支持和业务联系:info@testage.com.cn 电话:010-51297073

软件测试 | 领测国际ISTQBISTQB官网TMMiTMMi认证国际软件测试工程师认证领测软件测试网