如何将参数传递给ElapsedEventHandler调用的函数?
我的代码:
private static void InitTimer(int Index)
{
keepAlive[Index] = new Timer();
keepAlive[Index].Interval = 3000;
keepAlive[Index].Elapsed += new ElapsedEventHandler(keepAlive_Elapsed[, Index]);
keepAlive[Index].Start();
}
public static void keepAlive_Elapsed(object sender, EventArgs e[, int Index])
{
PacketWriter writer = new PacketWriter();
writer.AppendString("KEEPALIVE|.\\");
ServerSocket.Send(writer.getWorkspace(), Index);
ServerSocket.DisconnectSocket(Index);
}
我想要做的是在括号([和])之间。 但只是这样做显然不起作用......
答案 0 :(得分:43)
您无法在方法本身内执行此操作 - 您必须使事件处理程序有效地了解其上下文。最简单的方法是使用lambda表达式或匿名方法:
private static void InitTimer(int Index)
{
keepAlive[Index] = new Timer();
keepAlive[Index].Interval = 3000;
keepAlive[Index].Elapsed += delegate { KeepAliveElapsed(Index); };
keepAlive[Index].Start();
}
public static void KeepAliveElapsed(int Index)
{
PacketWriter writer = new PacketWriter();
writer.AppendString("KEEPALIVE|.\\");
ServerSocket.Send(writer.getWorkspace(), Index);
ServerSocket.DisconnectSocket(Index);
}
此处,匿名方法(带有delegate
关键字的位)创建了一个委托,该委托知道Index
InitTimer
参数。它只调用KeepAliveElapsed
方法。我使用了匿名方法语法,因为你不需要发送者或事件args;如果 需要它们,我可能会使用lambda表达式,例如
private static void InitTimer(int Index)
{
keepAlive[Index] = new Timer();
keepAlive[Index].Interval = 3000;
keepAlive[Index].Elapsed += (sender, args) => KeepAliveElapsed(sender, Index);
keepAlive[Index].Start();
}
public static void KeepAliveElapsed(object sender, int Index)
{
PacketWriter writer = new PacketWriter();
writer.AppendString("KEEPALIVE|.\\" + sender);
ServerSocket.Send(writer.getWorkspace(), Index);
ServerSocket.DisconnectSocket(Index);
}
(请注意,传统上Index
参数应该被称为index
,顺便说一句。)