公司有两个员工和一个主管,老板让主管好好看着两员工工作,一旦发现玩游戏的就狠狠的扣工资.可是还是有这不怕死的送上来.
在这定义两个员工的实体类,我们认为是客户端. 主管类就是服务器端.客户端提供委托接口,在服务器端注册.
代码如下,很多还有待改进:
ClientA.cs

Code
1
using System;
2
using System.Collections.Generic;
3
using System.Text;
4
5
namespace TestDelegate
6

{
7
class ClientA
8
{
9
public delegate void PlayGameDelgateA(Object sender, EventArgs e);
10
public event PlayGameDelgateA PlayGameEventA;
11
12
private int moneyNum;
13
public int MoneyNum
14
{
15
get
{ return moneyNum; }
16
set
{ moneyNum = value; }
17
}
18
public ClientA()
19
{
20
this.MoneyNum=1000;
21
Console.WriteLine("我是小张。我有{0}块",this.MoneyNum);
22
}
23
24
public void PlayGame()
25
{
26
Console.WriteLine("开始玩游戏咯。。。");
27
EventArgs e=new EventArgs();//参数设置,这里并没有传递参数。也可以继承EventArgs对象,增加更加复杂的参数类型
28
if (PlayGameEventA != null)
29
{
30
PlayGameEventA(this, e);
31
}
32
33
34
}
35
36
}
37
}
38
ClientB.cs

Code
1
using System;
2
using System.Collections.Generic;
3
using System.Text;
4
5
namespace TestDelegate
6

{
7
class ClientB
8
{
9
public delegate void PlayGameDelgateB(Object sender, EventArgs e);
10
public event PlayGameDelgateB PlayGameEventB;
11
12
private int moneyNum;
13
public int MoneyNum
14
{
15
get
{ return moneyNum; }
16
set
{ moneyNum = value; }
17
}
18
public ClientB()
19
{
20
this.MoneyNum=1000;
21
Console.WriteLine("我是小刘。我有{0}块",this.MoneyNum);
22
}
23
24
public void PlayGame()
25
{
26
Console.WriteLine("开始玩游戏咯。。。");
27
EventArgs e=new EventArgs();
28
if (PlayGameEventB != null)
29
{
30
PlayGameEventB(this, e);
31
32
}
33
34
35
}
36
}
37
}
38
接下来是服务器端的调用
Server.cs

Code
1
using System;
2
using System.Collections.Generic;
3
using System.Text;
4
5
namespace TestDelegate
6

{
7
class Server
8
{
9
10
static void Main(string[] args)
11
{
12
13
Console.WriteLine("游戏开始。。。");
14
ClientA A = new ClientA();
15
A.PlayGameEventA+=new ClientA.PlayGameDelgateA(DivMoneyNum);
16
A.PlayGame();
17
ClientB B = new ClientB();
18
B.PlayGameEventB += new ClientB.PlayGameDelgateB(DivMoneyNum);
19
B.PlayGame();
20
Console.WriteLine("游戏结束。。。");
21
Console.ReadKey();
22
23
}
24
25
static void DivMoneyNum(Object sender,EventArgs e) // 这里可以作为两个方法来写 相应注册的时候注册不同的方法 程序的结构更加清楚。
26
{
27
Console.WriteLine("有人玩游戏!钱多拉
;\n我看你有多少钱扣.");
28
Console.WriteLine("开始扣钱
一次500块");
29
if (sender is ClientA) //区分不同对象
30
{
31
ClientA zhang = (ClientA)sender;
32
zhang.MoneyNum = zhang.MoneyNum - 500;
33
Console.WriteLine("小张还剩下{0}块。", zhang.MoneyNum);
34
35
}
36
else if (sender is ClientB)
37
{
38
ClientB liu = (ClientB)sender;
39
liu.MoneyNum = liu.MoneyNum - 500;
40
Console.WriteLine("小刘还剩下{0}块。", liu.MoneyNum);
41
42
}
43
44
}
45
46
}
47
}
48