问题:
学习SerialPort类使用,查看了https://github.com/wangminli/SerialPortConnection代码,运行出现异常。单步调试发现,没有可用的串口时,str不为null。
解决方式:
在使用SerialPort.GetPortNames()时,要注意如果此时没有可用的串口,GetPortNames()会返回一个new String[0],所以不能通过如下str==null来判断是否存在可用的串口。
//检查是否含有串口
string[] str = SerialPort.GetPortNames();
if (str == null)
{
MessageBox.Show("本机没有串口!", "Error");
return;
}
而需要使用如下代码
//检查是否含有串口
string[] str = SerialPort.GetPortNames();
if (str.Length < 1)
{
MessageBox.Show("本机没有串口!", "Error");
return;
}
.net关于GetPortNames()函数的源码如下:
// If serialKey didn't exist for some reason
if (portNames == null)
portNames = new String[0];
return portNames;
在使用一个方法之前,多看看.net参考源码,地址如下:https://referencesource.microsoft.com/#System/sys/system/io/ports/SerialPort.cs
在使用C#的SerialPort类时,遇到当无可用串口时,SerialPort.GetPortNames()返回new String[0]而非null的问题。解决办法是检查返回数组的长度而非直接比较是否为null。建议在使用.NET方法前查阅官方源码以了解其行为。
6325

被折叠的 条评论
为什么被折叠?



