Events Sample Code(1)

此博客展示了 C# 代码中事件的使用。定义了一个包含事件实例的类,有声明、包含和触发事件的方法。另一个类对该事件进行注册,当事件触发时执行相应操作,通过代码示例清晰呈现了 C# 事件机制。

using System;

namespace ConsoleApp_CS
{

 class 小弟
 {
  //1.聲明事件實例
  public event EventHandler 挨扁;

  //2.包含事件
  private void 挨扁了(EventArgs e)
  {
   if(this.挨扁 != null)
    this.挨扁(this, e);
  }

  //3.觸發事件
  public void 被扁()
  {
   Console.WriteLine("被扁ing...");
   this.挨扁了(EventArgs.Empty);
  }
 }

 class 我
 {
  private 小弟 我小弟 = null;

  public 我(小弟 小小弟)
  {
   this.我小弟 = 小小弟;

   //註冊事件
   this.我小弟.挨扁 += new EventHandler(this.担心);
  }

  public void 担心(object sender, EventArgs e)
  {
   Console.WriteLine("我担心");
  }
 }

 class InstanceDelegate
 {
  [STAThread]
  public static void Main ()    
  {   
   小弟 小弟弟 = new 小弟();
   我 大哥 = new 我(小弟弟);
   小弟弟.被扁();
   Console.ReadLine();
  }    //end of main
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值