SerialPort 已打开但在 BytesToRead 上抛出 NullReferenceException

SerialPort is Open but throws NullReferenceException on BytesToRead

我创建了一个 SerialPort,可以检查它不为空,并且 SerialPort.IsOpen() returns 为真。 但是当我检查 BytesToRead 属性 时,我得到一个 NullReferenceException。

NullReferenceException: Object reference not set to an instance of an object
  System.IO.Ports.WinSerialStream.get_BytesToRead ()
  System.IO.Ports.SerialPort.get_BytesToRead ()
  (wrapper remoting-invoke-with-check) 
  System.IO.Ports.SerialPort:get_BytesToRead ()
  ...

我可以单步执行调试器并在调用 BytesToRead 之前立即看到,串行端口已实例化并打开,但调试器无法访问某些属性,包括 BytesToRead。

"System.IO.Ports.SerialPort"
    base: "System.IO.Ports.SerialPort"
    BaseStream: {System.IO.Ports.WinSerialStream}
    BaudRate: 9600
    BreakState: false
    BytesToRead: System.NullReferenceException: Object reference not set to an instance of an object
    BytesToWrite: System.NullReferenceException: Object reference not set to an instance of an object
    CDHolding: false
    CtsHolding: true
    DataBits: 8
    DiscardNull: System.NotImplementedException: The requested feature is not implemented.
    DsrHolding: false
    DtrEnable: false
    Encoding: {System.Text.ASCIIEncoding}
    Handshake: None
    IsOpen: true
    NewLine: "\r\n"
    Parity: None
    ParityReplace: System.NotImplementedException: The requested feature is not implemented.
    PortName: "COM3"
    ReadBufferSize: 4096
    ReadTimeout: 50
    ReceivedBytesThreshold: System.NotImplementedException: The requested feature is not implemented.
    RtsEnable: false
    StopBits: One
    WriteBufferSize: 2048
    WriteTimeout: -1

可能出了什么问题?

这似乎是 Unity 自 2016 年以来的一个错误。 他们 "Postponed" 正在处理它。

解决方法是使用实​​验性 .NET 4.6 版本,前提是您可以在项目中迁移到该版本而不会出现其他问题。

https://issuetracker.unity3d.com/issues/serialport-bytestoread-returns-null-reference