gpt4 book ai didi

c# - 触发事件时出现 NullReferenceException

转载 作者:IT王子 更新时间:2023-10-29 04:41:22 26 4
gpt4 key购买 nike

考虑以下几点:

class Client
{
public static event EventHandler connectFailed;

private Socket socket;

public Client()
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint endpoint = new IPEndpoint(
IPAddress.Parse("192.168.1.100"),
7900
);

try
{
socket.Connect(endpoint);
}
catch(Exception e)
{
connectFailed(e, new EventArgs());
}
}
}

假设其余代码已实现(Program.cs 中的事件处理程序等)。

我在 connectFailed(e, new EventArgs()); 行遇到了 NullRefrerenceException 问题,我不明白为什么。我的所有其他事件都正常触发,我看不出这有什么不同。

有什么想法吗?

最佳答案

您需要一个 null 检查 - 在 C# 中,当没有在该事件上注册任何处理程序时,您不能调用该事件。

通常的做法是实现一个 OnConnectFailed 方法:

protected virtual void OnConnectFailed(e as EventArgs) {
EventHandler tmp = connectFailed;
if(tmp != null)
tmp(this,e);
}

此外,事件处理程序的第一个参数应该是this,而不是异常。如果您需要将异常传递给事件处理程序,请创建一个具有异常属性的 EventArgs 类。

此外,从构造函数中引发事件没有意义……没有机会向其添加处理程序。

关于c# - 触发事件时出现 NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5766979/

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