C#委托-事件示例
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Event_Delegate
{
class Program
{
static void Main(string[] args)
{
A a = new A(); //定义首领A
B b = new B(a);
a.Raise("左");
Console.ReadLine();
//====
var test = new Heater();
test.Onboiled += TestOnboiled;
test.Onboiled += TestOnboiled;
test.Begin();
Console.ReadKey();
}
static void TestOnboiled(object sender, EventArgs e)
{
Console.WriteLine("Hello 事件被调用");
}
}
public delegate void RaiseEventHandler(string hand);
/// <summary>
/// 首领A
/// </summary>
public class A
{
/// <summary>
/// 首领A举杯事件
/// </summary>
public event RaiseEventHandler RaiseEvent;
public void Raise(string hand)
{
Console.WriteLine("首领A举杯");
//调用举杯事件,传入左或右手作为参数
if (RaiseEvent != null)
{
RaiseEvent(hand);
}
}
}
/// <summary>
/// 部下B
/// </summary>
public class B
{
A a;
public B(A a)
{
this.a = a;
a.RaiseEvent += new RaiseEventHandler(a_raiseEvent);
}
void a_raiseEvent(string hand)
{
if (hand.Equals("左"))
{
Console.WriteLine("部下B发起攻击 ");
}
}
}
}
Client_1.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace Event_Delegate
{
class Client_1
{
}
public class Heater
{
public event EventHandler Onboiled;
private void RasieBoiledEvent()
{
if (Onboiled == null)
{
Console.WriteLine("加热完成,处理订阅事件为空");
}
else
{
Onboiled(this,new EventArgs());
}
}
private Thread heatThread;
public void Begin()
{
heatTime = 5;
heatThread = new Thread(new ThreadStart(Heat));
heatThread.Start();
Console.WriteLine("加热器已经开启",heatTime);
}
private int heatTime;
private void Heat()
{
while (true)
{
Console.WriteLine("加热还需要{0} 秒",heatTime);
if (heatTime == 0)
{
RasieBoiledEvent();
return;
}
heatTime--;
Thread.Sleep(1000);
}
}
}
}
最新文章
- 图像处理中任意核卷积(matlab中conv2函数)的快速实现。
- 设置Android Studio启动时可选最近打开过的工程
- maven 错误: 程序包org.junit不存在
- Spring.Net Remoting 相关使用
- PC缺少一个或多个网络协议 qq可登录(win10)
- sed命令的基本使用
- Lotus开发性能优化
- C#关闭word进程
- 在RHEL5.2 64bit下编译安装log4cxx错误
- mysql 事件调度器
- leetcode 239 Sliding Window Maximum
- Xcode 断点调试,取消直接进入到汇编语言界面处理
- c# WMI获取机器硬件信息(硬盘,cpu,内存等)
- C++安装失败解决办法
- 经历:Java中字符串中按照多个字符拆分或替换:split()和replaceAll()
- Git命令详解(一)-个人使用
- Oracle视图基础
- LCS小结(O(∩_∩)O~吽吽)
- <;a href=";#"; onclick=";history.back();";>;<;/a>;这样写为什么是对的? -(转)
- USACO刷题之路