using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication2
{
//先定义一个委托
public delegate void APlayGameHandle(object sender, System.EventArgs e);
class Program
{
static void Main(string[] args)
{
A a = new A();//实例化A
B b = new B();//实例化B
//监视A Play Game 事件
a.APlayGame += new APlayGameHandle(b.KouQian);
//A执行玩游戏事件
a.PlayGame();
}
}
class A
{
//定义APlayGame事件
public event APlayGameHandle APlayGame;
//A的构造函数,初始化A有1000元
public A()
{
iMoney = 1000;
}
//声明A的 iMoney属性
public int iMoney { get; set; }
protected virtual void OnPlayGame(EventArgs e)
{
if (APlayGame != null)
{
APlayGame(this, e);
}
}
public void PlayGame()
{
Console.Write("开始玩游戏了");
EventArgs e = new EventArgs();
OnPlayGame(e);
}
}
class B
{
//执行扣钱操作
public void KouQian(object sender,System.EventArgs e)
{
A a = (A)sender;
Console.WriteLine("A的钱: " + a.iMoney);
Console.WriteLine("开始扣钱......");
System.Threading.Thread.Sleep(500);
a.iMoney = a.iMoney - 10;
Console.WriteLine("扣完了....现在小张还剩下:" + a.iMoney);
}
}
}
委托的一段示例代码
最新推荐文章于 2024-08-29 12:21:32 发布