我在C#.NET中有一个应用程序,它具有 MainForm 和几个类。
I have an application in C# .NET which has a MainForm and a few classes.
其中一个这些类从网络接收传入的数据消息。我需要将这些消息的文本附加到 MainForm 上的多行文本框中。
One of these classes receives incoming data messages from a network. I need to get these message's text appended into a multi-line textbox on the MainForm.
我可以发送通过将方法设为静态,将消息发送到 MainForm 中的方法,但是静态方法无法访问 MainForm
I can send the message to a method in the MainForm by making the method static, but then the static method cannot access the MainForm's controls.
TheIncomingDataClass.cs
namespace TheApplicationName { class TheIncomingDataClass { public void IncomingMessage(IncomingMessageType message) { TheApplicationName.MainForm.ReceiveMSG(message); }MainForm.cs
public static void ReceiveMSG(string message) { txtDisplayMessages.AppendText(message); //This line causes compile error }编译错误:
非静态字段,方法或属性'TheApplicationName.MainForm.txtDisplayMessages'需要对象引用
An object reference is required for the nonstatic field, method, or property 'TheApplicationName.MainForm.txtDisplayMessages'
推荐答案
静态方法无法访问txtDisplayMessages之类的成员,因为它不是该实例的一部分。我建议您对静态方法的概念有所了解,因为这是一个与语言无关的概念。最好通过删除static修饰符来实现该方法,因为它不需要是静态的-看来它需要由该对象的特定实例调用。
A static method doesn't have access to members like txtDisplayMessages because it is not a part of that instance. I suggest you do some reading on the concepts of static methods and whatnot, because that is a fairly language agnostic concept. That method would best be served by removing the static modifier, because it doesn't need to be static - it appears that it would need to be called by that particular instance of that object.
更多推荐
如何从静态方法访问控件?
发布评论