赵工的个人空间


网络课堂部分转编程技巧部分转编程演练

 C#编程技巧

首页 > 网络课堂 > C#编程技巧 > C#编程中使用委托
C#编程中使用委托
C#编程是使用多线程的,在Window窗口应用程序中,为了较快响应用户的操作,有单独的线程进行界面处理,而非界面的一些操作则会使用另外的线程。这种情况下,如果其他线程要更改窗口界面,比如接收到的数据在窗口上显示出来、事件的处理函数等,往往都要使用委托,不然会有错误提示。
1)不传递数据的委托:
比如在串口接收数据的事件处理函数中使用委托:
  private void DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
  {
     txtDataReceived.BeginInvoke(new myDelegate(updateTextBox));
  }

这样,当串口接收到数据后,就会使用委托方式显示在txtDataReceived文本框中。而委托的代码为:
  public delegate void myDelegate();
  public void updateTextBox()
  {
     txtDataReceived.AppendText(serialPort.ReadExisting());
     txtDataReceived.ScrollToCaret();
  }

这样定义的委托,并没有传递数据,而是在界面的显示函数中使用serialPort.ReadExisting()方法读取数据,这是一种比较简单的委托方式。
2)传递数据的委托:
很多情况下,需要在使用委托时把得到的数据传递出去,就需要使用传递数据的委托:
  txtDataReceived.BeginInvoke(new delegateParam(UpdateTextBox), byData);
上述代码,把接收到的数据通过委托传递到窗口界面的txtDataReceived文本框中,其中byData为存储了接收数据的字节数组。这时就要定义一个带参数的委托来处理:
  public delegate void delegateParam(byte[] rcvBuf);
  public void UpdateTextBox(byte[] rcv)
  {
     strAppend = ByteArrayToHexString(rcv) + Environment.NewLine;
     txtDataReceived.AppendText(strAppend);
     txtDataReceived.ScrollToCaret();
  }

相应的函数中的参数皆为字节数组,这样就可以把byData数据传递到窗口界面中。其中使用了自定义函数ByteArrayToHexString()将字节数组转换为对应的十六进制字符串:
  private string ByteArrayToHexString(byte[] data)
  {
     StringBuilder sb = new StringBuilder(data.Length * 3);
     foreach (byte b in data)
     {
       sb.Append(Convert.ToString(b, 16).PadLeft(2, '0'));
     }
     return sb.ToString().ToUpper();
  }


3)传递多个数据的委托:
委托也可以带有一串参数,比如:
  resultStr.BeginInvoke(new delegateLabel(UpdateLabel), numRight, numError, numSend, numRcv);
上述代码中,为了在窗口的名为resultStr的Label中显示相应数据,传递了4个参数。对应的委托定义代码为:
  public delegate void delegateLabel(int num1, int num2, int num3, int num4);
  public void UpdateLabel(int num1, int num2, int num3, int num4)
  {
     resultStr.Text="发送"+num3.ToString()+"指令,接收到"+num4.ToString()+"数据,正确:"+num1.ToString()+",错误:"+num2.ToString();
  }

上述代码中使用的是4个整型变量,对应的函数中的参数也都是整型。当然也可以传递其他类型的数据,只需要进行相应的定义即可实现。
Copyright@dwenzhao.cn All Rights Reserved   备案号:粤ICP备15026949号
联系邮箱:dwenzhao@163.com  QQ:1608288659