从指向一个方法的另一个类访问委托? [英] accessing delegate from another class which points to a method?
本文介绍了从指向一个方法的另一个类访问委托?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用VS2010,我正在忙着编写聊天应用程序.在我的连接"类中,我有一个读取接收消息的方法.在我的表单"代码中,我有一种方法可以用收到的最新消息更新文本框(多行).当连接类中的"ReadMessage"方法完成读取后,如何使用委托指向"AppendTextBox"?
这是我的一些代码:
Using VS2010, I am busy writing a chat application. In my class "Connection", I have a method which reads the receiving messages. In my "form''s" code, I have a method that updates the textbox (which is multi line) with the newest message received. How do I go about using a delegate to point to the "AppendTextBox" when the "ReadMessage" method within the connection class is done reading?
Here is some of my code:
Class Connection
{
private void ReadMessages()
{
NetworkStream stream = tcpClient.GetStream();
if (stream.CanRead)
{
byte[] bytesToRead = new byte[1024];
StringBuilder completeMessage = new StringBuilder();
int numberOfBytesToRead = 0;
numberOfBytesToRead = stream.Read(bytesToRead, 0, bytesToRead.Length);
completeMessage.AppendFormat("{0}", Encoding.ASCII.GetString(bytesToRead, 0, numberOfBytesToRead));
}
}
}
Namespace Whatever
{
public delegate void _UpdateMyTextBox(string message);
public partial class Form1
{
public void AppendTextBox(string message)
{
txtMessages.AppendText(message + "\r\n");
}
}
}
推荐答案
您可以传递 ^ ],指向您的方法,并指向Connection类(可能通过构造函数).
在通知您的主表单时,您可以简单地使用字符串参数调用委托,并且指向的函数将被执行.有关某些示例,请在此处阅读 [
You can pass an instance of a delegate[^], pointing to your method, to the Connection Class (probably through the constructor).
At the time of notifying your main form you can simply call the delegate with a string parameter and the function it is pointing to will be executed. For some examples read here[^] (Action<T> is a delegate like your _UpdateMyTextBox).
Hope it helps :)
这篇关于从指向一个方法的另一个类访问委托?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文