C#,在静态方法中访问(获取或读取)textBox 值?
我有一个带有文本字段(textBox1)的表单(form1) 我有一个具有方法“public static string getValue()”的类,
如何在方法 getValue() 中读取 textBox1 的值?
这是我的代码,
namespace MyProgram
{
public partial class Form1: Form
{
---------------------------------
---------------------------------
---------------------------------
}
}
整个软件都是在这个结构中构建的另一个类
namespace MyProgram
{
class values
{
public static string getValues()
{
string v;
v = ------get value from textBox1 in Form1
return v;
}
}
}
,所以我希望 C# 中有一些标准方法可以在 getValue() 方法中获取这些值
I have a form (form1) that has a text field (textBox1)
I have a class that has the method "public static string getValue()"
how I can read the value of the textBox1 within the method getValue() ??
here is my code
namespace MyProgram
{
public partial class Form1: Form
{
---------------------------------
---------------------------------
---------------------------------
}
}
the other class
namespace MyProgram
{
class values
{
public static string getValues()
{
string v;
v = ------get value from textBox1 in Form1
return v;
}
}
}
the whol software is build in this structure, so I hope there is some standard way in C# to get these values in the method getValue()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你不能。该属性位于类的实例中,静态方法没有指向它的指针。被设计破坏了。
You can not. The property is in the instance of the class, the static method has no pointer to it. Broken by design.
您必须实例化 Form1 的新对象并获取值。或者在 form1 中添加一个委托并从 getValue 调用它,这样委托的返回值应该是文本框的值。
You have to instantiate new object of Form1 and get the value. Or else add a delegate in form1 and call it from getValue, such that the return value of delegate should be the textbox value.
您可以在静态方法内实例化、显示和处置表单。示例:
using 块负责释放为表单分配的资源。 ShowDialog 将表单显示为模式对话框。
虽然这适用于简单的对话框,但可能并不是您在每种情况下都希望这样做。该方法将阻塞当前线程,直到用户关闭表单。查看其他应用程序和示例代码。正如 @Dan Abramov 所写,重新考虑你的设计。
You can instantiate, show, and dispose of the form inside the static method. An example:
The using block takes care of freeing the resources allocated for the form. ShowDialog shows the form as a modal dialog.
While this works for simple dialog boxes, it is probably not what you want to do in every case. The method will block the current thread until the user closes the form. Look at other applications and sample code. As @Dan Abramov wrote, Reconsider your design.
但为什么不直接从表单中读取值呢?
考虑一下 KISS 原则!
But why don't you just read the value from the form?
Consider the KISS-principle!
几乎没有假设 - 您可以使用此代码片段
取决于您的其他代码,定义控件/变量“public”也很有帮助,例如:
...或使用 VS Studio GUI - 属性:
已测试;对比 2019 - NET 4.8 - 2022 年 1 月 29 日
With few assumptions - you can use this code snippet
Depend on your other code it is also helpful to define the control / variable "public" as for example:
... or use the VS Studio GUI - Properties:
Tested; VS 2019 - NET 4.8 - 1/29/2022