我正在尝试创建一种人工智能,用于从我的网络服务器收集信息。
我有一个按钮可以开启和关闭AI,还有一些方法用于传递参数以收集信息。当AI开启时,它会触发我创建的一个事件系统,称为powerOn。我试图在RichTextBox中显示“hello”或类似的东西,但文本框在接收到指令后并未更新。
包含主方法的Program类:
namespace Universe_AI{public static class Program{ public static Boolean aiRunning = false; /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] public static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } public static void writeMemory(string header, string value) { } public static void readMemory() { } public static void AiProccess(string pType, String[] pArgs) { if (pType == "event") { string pEvent = pArgs[0]; aiEvent(pEvent); } } public static void aiEvent(string pEvent){ if (pEvent == "powerOn") { Form1 ele = new Form1(); ele.Mind.Text = "test"; ele.Mind.AppendText("Are you my Creator?"); } }}}
Form1类
namespace Universe_AI{public partial class Form1 : Form{ public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { if (Program.aiRunning == false) { Program.aiRunning = true; label2.Text = "ON"; String[] eventArgs = new String[] {"powerOn"}; Program.AiProccess("event", eventArgs); } else { Program.aiRunning = false; label2.Text = "OFF"; Mind.Text = ""; } } private void button2_Click(object sender, EventArgs e) { Mind.Text = "test"; }}}
名为Mind的RichTextBox是公共的,并且没有返回错误。测试按钮可以更新它,但从另一个类访问时似乎不起作用
回答:
这一行代码:
Form1 ele = new Form1();
创建了一个新的表单.. 以及其下的一切都是新的。这意味着你有一个新的,完全独立的表单,它在内存中有自己的RichTextBox
。你正在向这个新的RichTextBox追加文本。
你需要做的是,传递你当前正在使用的表单的实例。阅读这里的注释:
// 在末尾添加Form作为参数 ---------------> ___这里___public static void AiProccess(string pType, String[] pArgs, Form1 form){ if (pType == "event") { string pEvent = pArgs[0]; aiEvent(pEvent, form); // 传递它 }}public static void aiEvent(string pEvent, Form1 form){ if (pEvent == "powerOn") { // 使用“form”变量 form.Mind.Text = "test"; form.Mind.AppendText("Are you my Creator?"); }}
阅读代码中的注释。然后你可以像这样传递当前实例:
String[] eventArgs = new String[] {"powerOn"};Program.AiProccess("event", eventArgs, this); // <---- 传递“this”