嘿,我最近一直在使用c#和事件,但我剛剛開始創建自己的事件並使用它們。我有點困惑,爲什麼要使用event關鍵字,我只通過使用委託獲得了相同的結果。「event」的用途關鍵字
public partial class Form1 : Form
{
ServerConnection connection = new ServerConnection();
public Form1()
{
InitializeComponent();
connection.ref = new del(MethOne);
connection.ref += new del(MethTwo);
}
public void MethOne(object message)
{
MessageBox.Show((string)message);
}
public void MethTwo(object message)
{
MessageBox.Show((string)message);
}
}
public delegate void del(string message);
public class ServerConnection
{
private TcpListener tcpListener;
public del ref;
private List<NetworkStream> clientList = new List<NetworkStream>();
public ServerConnection()
{
this.tcpListener = new TcpListener(IPAddress.Any, 3000);
ThreadStart startListening = new ThreadStart(ListenForClients);
Thread startThread = new Thread(startListening);
startThread.Start();
}
public void ListenForClients()
{
tcpListener.Start();
ParameterizedThreadStart handleClient = new ParameterizedThreadStart(HandleClient);
while (true)
{
TcpClient newClient = tcpListener.AcceptTcpClient();
Thread handleClientThread = new Thread(handleClient);
handleClientThread.Start(newClient);
}
}
public void HandleClient(object newClient)
{
NetworkStream clientStream = ((TcpClient)newClient).GetStream();
clientList.Add(clientStream);
BinaryFormatter formatter = new BinaryFormatter();
string message;
while (true)
{
message = (string)formatter.Deserialize(clientStream);
ref((string)message);
}
}
哦,我的......這似乎是一個合理的問題。爲什麼downvote?爲什麼關閉它? –