0

Action<T> Delegate用来在类和表单之间建立联系。该类连接到串行端口,接收到的数据显示在表单中。在Action<T> Delegate表单中封装了一个显示接收到的数据的方法。但是委托总是显示null,没有封装方法。

课程代码是:

 public SerialPort mySerialPort;

    public Action<byte[]> DataReceived_Del;             //delegate for data recieved

    public string connect()
    {
        try
        {

            mySerialPort = new SerialPort("COM14");
            mySerialPort.BaudRate = 115200;
            mySerialPort.DataBits = 8;
            mySerialPort.Parity = System.IO.Ports.Parity.None;
            mySerialPort.StopBits = System.IO.Ports.StopBits.One;
            mySerialPort.RtsEnable = false;

            mySerialPort.DataReceived += mySerialPort_DataReceived;
            mySerialPort.Open();

        }
        catch (SystemException ex)
        {
            MessageBox.Show(ex.Message);
        }
        if (mySerialPort.IsOpen)
        {
            return "Connected";
        }
        else
        {
            return "Disconnected";
        }
    }


    //serial port data recieved handler
    public void mySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        try
        {
            //no. of data at the port
            int ByteToRead = mySerialPort.BytesToRead;

            //create array to store buffer data
            byte[] inputData = new byte[ByteToRead];

            //read the data and store
            mySerialPort.Read(inputData, 0, ByteToRead);


            var copy = DataReceived_Del;
            if (copy != null) copy(inputData); 

        }
        catch (SystemException ex)
        {
            MessageBox.Show(ex.Message, "Data Received Event");
        }
    }

在我们显示数据的表格中:

 public Form1()
    {
        InitializeComponent();
        Processes newprocess = new Processes();
        newprocess.DataReceived_Del += Display;


    }

    //Display
    public void Display(byte[] inputData)
    {
        try
        {
            Invoke(new Action(() => TboxDisp.AppendText((BitConverter.ToString(inputData)))));
        }
        catch (SystemException ex)
        {
            MessageBox.Show(ex.Message, "Display section");
        }
    }

DataReceived_Del本来应该封装方法的,Display但确实如此NULL

我看不到发生了什么。。

任何帮助表示赞赏..

4

2 回答 2

1

您应该在构造函数之外定义 newprocess ,这可能会解决

Processes newprocess;
public Form1()
{
    InitializeComponent();
    newprocess = new Processes();
    newprocess.DataReceived_Del += Display;


}
于 2013-03-19T08:11:18.843 回答
0

您正在使用 += 添加到委托,但委托开始时为 NULL。我不确定这会奏效。我会尝试 = 而不是 +=。

public Form1() {
    InitializeComponent();
    Processes newprocess = new Processes();
    newprocess.DataReceived_Del = Display;
}
于 2013-03-19T08:32:17.523 回答