如何从静态方法访问控件?

编程入门 行业动态 更新时间:2024-10-24 18:24:45
本文介绍了如何从静态方法访问控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在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.

更多推荐

如何从静态方法访问控件?

本文发布于:2023-07-15 10:21:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1110636.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控件   静态   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!