gpt4 book ai didi

C#:字符串作为事件的参数?

转载 作者:太空狗 更新时间:2023-10-29 17:30:39 26 4
gpt4 key购买 nike

我有一个用于表单的 GUI 线程和另一个用于计算事物的线程。

表单有一个 richtTextBox。我希望工作线程将字符串传递给表单,以便每个字符串都显示在文本框中。

每次在工作线程中生成一个新字符串时,我都会调用一个事件,现在应该会显示该字符串。但我不知道如何传递字符串!到目前为止,这是我尝试过的:

///// Form1
private void btn_myClass_Click(object sender, EventArgs e)
{
myClass myObj = new myClass();
myObj.NewListEntry += myObj_NewListEntry;
Thread thrmyClass = new Thread(new ThreadStart(myObj.ThreadMethod));
thrmyClass.Start();
}

private void myObj_NewListEntry(Object objSender, EventArgs e)
{
this.BeginInvoke((MethodInvoker)delegate
{
// Here I want to add my string from the worker-thread to the textbox!
richTextBox1.Text += "TEXT"; // I want: richTextBox1.Text += myStringFromWorkerThread;
});
}

///// myClass (working thread...)
class myClass
{
public event EventHandler NewListEntry;

public void ThreadMethod()
{
DoSomething();
}

protected virtual void OnNewListEntry(EventArgs e)
{
EventHandler newListEntry = NewListEntry;
if (newListEntry != null)
{
newListEntry(this, e);
}
}

private void DoSomething()
{
///// Do some things and generate strings, such as "test"...
string test = "test";


// Here I want to pass the "test"-string! But how to do that??
OnNewListEntry(EventArgs.Empty); // I want: OnNewListEntry(test);
}
}

最佳答案

像这样

public class NewListEntryEventArgs : EventArgs
{
private readonly string test;

public NewListEntryEventArgs(string test)
{
this.test = test;
}

public string Test
{
get { return this.test; }
}
}

然后你这样声明你的类

class MyClass
{
public delegate void NewListEntryEventHandler(
object sender,
NewListEntryEventArgs args);

public event NewListEntryEventHandler NewListEntry;

protected virtual void OnNewListEntry(string test)
{
if (NewListEntry != null)
{
NewListEntry(this, new NewListEntryEventArgs(test));
}
}
}

并在订阅 Form

private void btn_myClass_Click(object sender, EventArgs e)
{
MyClass myClass = new MyClass();
myClass.NewListEntry += NewListEntryEventHandler;
...
}

private void NewListEntryEventHandler(
object sender,
NewListEntryEventArgs e)
{
if (richTextBox1.InvokeRequired)
{
this.Invoke((MethodInvoker)delegate
{
this.NewListEntryEventHandler(sender, e);
});
return;
}

richTextBox1.Text += e.Test;
}

我冒昧地使 NewListEntryEventArgs 类不可变,因为这是有道理的。我还部分更正了您的命名约定,在适当的地方进行了简化和更正。

关于C#:字符串作为事件的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12055431/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com