我对C#有点新意,当串口通信操作中串口连接丢失时,我最近遇到了“无效操作异常”的问题。我试图通过private void port_ErrorReceived
捕获错误(见下文),但我一直收到一条错误,指出“不包含带有1个参数的构造函数”。
private void port_ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
{
bool error = false;
// Check if the comport is closed
if (!comport.IsOpen)
{
try
{
// Try to open the port
comport.Open();
}
catch (UnauthorizedAccessException) { error = true; }
catch (IOException) { error = true; }
catch (ArgumentException) { error = true; }
catch (InvalidOperationException) { error = true; }
if (error) MessageBox.Show(this, "No serial port identified. Please check your connection.", "Serial Connection Lost", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
}
这是我调用新事件处理程序的地方:
comport.ErrorReceived += new SerialErrorReceivedEventArgs(port_ErrorReceived);
我在StackOverflow上看过一些类似的帖子,但我不太确定适用于这种情况的内容。任何帮助,将不胜感激。谢谢。
答案 0 :(得分:1)
我认为你的意思是:
comport.ErrorReceived += port_ErrorReceived;
或更详细地说:
comport.ErrorReceived += new SerialErrorReceivedEventHandler(port_ErrorReceived);
(但它们是相同的;没有理由不使用第一个版本)