.Net-动作<t>代表错误?</t>

时间:2013-03-19 07:45:53

标签: c# events delegates event-handling

我使用Action<T> Delegate在class和Form之间建立链接。类连接到串行端口,接收的数据显示在表单中。 Action<T> Delegate封装了Form中显示接收数据的方法。但委托始终显示为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

我看不出发生了什么......

感谢任何帮助..

2 个答案:

答案 0 :(得分:1)

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

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


}

答案 1 :(得分:0)

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

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