问题描述
我在C#.NET具有的MainForm和一些类的应用程序。
一这些类从网络接收传入的数据消息。
我需要得到这些消息的文本追加到在MainForm中多行文本框。
我可以通过使静态方法将消息发送到一个方法MainForm的,但静态方法不能访问的MainForm的控制。
I have an application in C# .net which has a MainForm and a few classes.
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.
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
TheIncomingDataClass.cs
namespace TheApplicationName
{
class TheIncomingDataClass
{
public void IncomingMessage(IncomingMessageType message)
{
TheApplicationName.MainForm.ReceiveMSG(message);
}
MainForm.cs
MainForm.cs
public static void ReceiveMSG(string message)
{
txtDisplayMessages.AppendText(message); //This line causes compile error
}
编译错误:
对象引用是必需的非静态字段,方法或属性TheApplicationName.MainForm.txtDisplayMessages
The compile error:
An object reference is required for the nonstatic field, method, or property 'TheApplicationName.MainForm.txtDisplayMessages'
任何帮助是AP preciated。
Any help is appreciated.
我还是蛮一个C#初学者所以请您描述。
I am still quite a C# beginner so please be descriptive.
在此先感谢。
推荐答案
一个静态方法没有获得像txtDisplayMessages成员,因为它不是该实例的一部分。我建议你做的静态方法和诸如此类的概念,一些阅读,因为这是一个相当语言无关的概念。该方法将最好通过去除静态修饰符送达,因为它并不需要是静态的。 - 看来,它需要由该对象的该特定实例被称为
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.
这篇关于在C#.NET,一个人怎么访问从静态方法的控制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!