gpt4 book ai didi

c# - "event"关键字的用途

转载 作者:太空狗 更新时间:2023-10-29 18:13:32 24 4
gpt4 key购买 nike

我最近经常使用 C# 和事件,但我才刚刚开始创建自己的事件并使用它们。我对为什么要使用 event 关键字有点困惑,我只使用委托(delegate)得到了相同的结果。

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);
}
}

最佳答案

event 关键字让您可以在声明中指定addremove 操作。

private Action _myEvent;

public event Action MyEvent
{
add
{
Console.WriteLine("Listener added!");
_myEvent += value;
}
remove
{
Console.WriteLine("Listener removed!");
_myEvent -= value;
}
}

关于c# - "event"关键字的用途,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13023323/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com