前段日子,在学习C#中委托与事件,理解得不是很清楚,直到在园子里看到一篇博客,用了热水器的一件例子讲解委托与事件,才让我恍然大悟。
然后就利用委托与事件写了一个两人互聊的小程序。
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace Chat
{
class ChatEventArgs:EventArgs
{
public string ChatMsg;
public ChatEventArgs(string msg)
{
ChatMsg=msg;
}
}
class Chater
{
public string name;
public delegate void ChatEventHandler(object sender, ChatEventArgs e);
public event ChatEventHandler Chat;
public static Queue MsgQueue;
public Chater(string name)
{
this.name = name;
if (MsgQueue == null)
MsgQueue = new Queue();
}
private void OnChat(ChatEventArgs e)
{
if (Chat != null)
Chat(this, e);
}
private void ShowAllMsg()
{
Console.Clear();
foreach (string msg in MsgQueue)
Console.WriteLine(msg);
Console.WriteLine("----------------------------");
}
private void ChatMsgQueue(string name, string msg)
{
if (MsgQueue.Count >= 12)
{
MsgQueue.Dequeue();
MsgQueue.Dequeue();
}
MsgQueue.Enqueue(name + ":");
MsgQueue.Enqueue(" " + msg);
ShowAllMsg();
}
public void Chatting(object sender, ChatEventArgs e)
{
string name = ((Chater)sender).name;
ChatMsgQueue(name, e.ChatMsg);
Console.Write("{0} says \"{1}\" to you, what do you want to reply: ", name, e.ChatMsg);
string replysContent = Console.ReadLine();
if (replysContent != "exit" && replysContent != "I'm tired!")
{
ChatEventArgs replys = new ChatEventArgs(replysContent);
OnChat(replys);
}
else
return;
}
public void StartChat()
{
Console.WriteLine("Okay, let's starting chatting!");
Console.WriteLine("My name is {0}, I get starting!",name);
string start = Console.ReadLine();
if (start != "exit" && start != "I'm tired!")
{
ChatEventArgs startMsg = new ChatEventArgs(start);
OnChat(startMsg);
}
else
return;
}
}
class Program
{
static void Main(string[] args)
{
Chater PersonA = new Chater("Jobs");
Chater PersonB = new Chater("Eric");
PersonA.Chat += PersonB.Chatting;
PersonB.Chat += PersonA.Chatting;
PersonA.StartChat();
}
}
}
程序运行结果: