请考虑以下几点:
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
的问题,我不明白为什么。我的所有其他事件都触发得很好,我看不出这有什么不同。
有什么想法吗?
发布于 2011-04-24 05:14:46
你需要一个空的签入C#,当事件上没有注册的处理程序时,你不能调用事件。
通常的做法是实现一个OnConnectFailed方法:
protected virtual void OnConnectFailed(e as EventArgs) {
EventHandler tmp = connectFailed;
if(tmp != null)
tmp(this,e);
}
此外,事件处理程序的第一个参数应为this
,而不是exception。如果需要将异常传递给事件处理程序,请使用exception属性创建一个EventArgs
类。
此外,从构造函数引发事件也没有意义...没有任何东西有机会向它添加处理程序。
发布于 2013-12-17 14:29:01
找到了,
public delegate void OnRequestReceivedHandler(object sender);
public event OnRequestReceivedHandler ReqeustReceived = delegate { };
https://stackoverflow.com/questions/5766979
复制相似问题