串口响应缓冲区空问题C#

Serial port responder buffer null issue C#

我正在尝试用 C# 制作一个小型控制台程序,它模仿硬件,在其中以主从方式响应特定的发送命令。所以另一个程序(master)将发送一个字节数组,例如:0xFF, 0x00, 0xCD, 0x01, 0x00, 0x00, 0x00;我尝试制作的从控制台程序将检查这个接收到的字节数组,如果它的第三个元素是 0xCD 那么它将响应为 0xFF, 0x00, 0xCD, 0x01, 0x00, 0x00, 0x00.

这是我试过的整个程序:

using System.IO.Ports;
namespace ConsoleMyConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            SerialPort myPort = new SerialPort();

            byte[] message_to_receive = null;
            byte[] message_to_response = { 0xFF, 0x00, 0xCD, 0x01, 0x00, 0x00, 0x00 };
            myPort.PortName = "COM8";
            myPort.BaudRate = 9600;
            myPort.DataBits = 8;
            myPort.Parity = Parity.None;
            myPort.StopBits = StopBits.One;

            myPort.Open();

            int received_bytes = myPort.BytesToRead;
            myPort.Read(message_to_receive, 0, received_bytes);

            if (message_to_receive[2] == 0xCD)
                myPort.Write(message_to_response, 0, message_to_response.Length);
        }
    }
}

但是当我 运行 这个程序时,我得到: System.ArgumentNullException: 'Buffer cannot be null 错误。我不知道为什么 myPort.Read 会发生这种情况。无论如何我都必须声明 message_to_receive,但无法让它发挥作用。

查看此规范页面。
SerialPort.Read Method

对于Read()参数中指定的缓冲区数组,必须提前准备好调用应用程序所需大小的区域。
与 ReadExisting()、ReadLine() 和 ReadTo() 不同,API 不准备字符串数据。

准备一个可能出现的最长数据大小的数组,或者准备一个较短的数组并根据需要多次重复 Read()。