C# 事件 示例 源代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleAppEventPro
{
//0.事件触发类
public class mm
{
//1.定义事件参数类
public class nn : EventArgs
{
public readonly char aa;
public nn(char Inputaa)
{
aa = Inputaa;
}
}
//2.定义委托delegate
public delegate void weituo(Object sender,nn e);

//3.用Event关键字声明事件对象
public event weituo TestEvent;

//4.事件触发方法
protected virtual void OnTestEvent(nn e)
{
if (TestEvent != null)
{
TestEvent(this, e);
}
}
//5.引发方法
public void RaiseEvent(char aa)
{
nn e = new nn(aa);
OnTestEvent(e);
}
}

//侦听事件的类
public class zz
{
//1.定义处理事件的方法,他与声明事件的delegate具有相同的参数和返回值类型——》事件处理方法
public void KeyPressed(object sender,mm.nn e)
{
Console.WriteLine("发送者为:{0},所按的键为:{1}",sender,e.aa);
}

//2.订阅事件
public void Subscribe(mm eventSource)
{
eventSource.TestEvent += new mm.weituo(KeyPressed);
}

//3.取消订阅
public void UnSubscribe(mm eventSource)
{
eventSource.TestEvent -= new mm.weituo(KeyPressed);
}
}

public class Test
{
public static void Main()
{
//创建事件源对象
mm es = new mm();
//创建侦听对象
zz el = new zz();

//订阅事件
Console.WriteLine("开始订阅事件");
el.Subscribe(es);

//引发事件
Console.WriteLine("输入一个字符,再按Enter键");

string s = Console.ReadLine();
es.RaiseEvent(s.ToCharArray()[0]);
//取消订阅事件
Console.WriteLine("开始取消订阅事件!");
el.UnSubscribe(es);
//引发事件
Console.WriteLine("输入一个字符,再按Enter键");
s = Console.ReadLine();
es.RaiseEvent(s.ToCharArray()[0]);
Console.ReadKey();
}
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值