2013-03-19 72 views
0

我使用Action<T> Delegate來建立類和表單之間的鏈接。該類連接到串行端口,並且接收到的數據以表格形式顯示。 Action<T> Delegate在顯示接收到的數據的表單中封裝了一個方法。但委託始終顯示爲空,不封裝該方法。.Net-行動<T>委託錯誤?

的類代碼爲:

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"); 
     } 
    } 

應該封裝方法DisplayDataReceived_Del,但它是NULL

我不能看到發生了什麼事..

任何幫助表示讚賞..

回答

1

應定義構造函數外newprocess,可能這將解決

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


} 
+0

仍然是一樣的..但我相信它與我調用委託的方式有關。 – Liban 2013-03-19 08:22:31

+0

'newprocess'變量可能具有'構造函數本地'作用域,但該對象仍然由事件引用。所以它不會被垃圾回收,所以它仍然可以工作,即使你不能在構造函數外使用newprocess變量。 – Maarten 2013-03-19 08:33:44

+0

@Maarten:問題中沒有事件 – TalentTuner 2013-03-19 08:36:55

0

你是使用+ =添加到委託,但該委託爲NULL開頭。我不確定這會起作用。我會嘗試=而不是+ =。

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

'='也沒有工作。 – Liban 2013-03-19 08:56:20