【发布时间】:2018-12-10 08:02:38
【问题描述】:
我正在努力在 C# 中为一个特殊问题传递一个变量(一个字符串):
概述:
我正在为我公司购买的程序编写插件。该程序(或更好:程序支持)为用户提供了基本的 C# 代码,它基本上只是打开一个表单,并将程序与我在表单代码中写下的任何内容连接起来。 因为它是一个 Visual-Studio-Solution 我得到一些文件:“MyUserInterface.cs”和“MyUserInterface.Designer.cs”。
“MyUserInterface.Designer.cs”定义了我的表单的外观,我的问题最重要的部分是:
partial class MyUserInterface
{
[...]
private void InitializeComponent()
{
[...]
this.f_status = new System.Windows.Forms.Label();
this.SuspendLayout();
[...]
//
// status
//
this.f_status.Name = "status";
this.f_status.Text = "WELCOME TO MYPLUGIN v2";
[...]
this.Controls.Add(this.f_status);
this.ResumeLayout(false);
this.PerformLayout();
}
[...]
private System.Windows.Forms.Label f_status;
[...]
}
“MyUserInterface.cs”中最重要的代码是:
partial class MyUserInterface
{
[...]
public MyUserInterface()
{
InitializeComponent();
}
[...]
private void click_compute(object sender, EventArgs e)
{
//Basically everythings runs here!
//The code is opend in other classes and other files
}
}
现在,正如我在代码部分中标记的那样,我的整个代码在“点击计算”函数中运行,并被“外包”到其他类中。
我的代码的一个重要部分位于“statushandler.cs”中:
class statushandler
{
[...]
public static void status_msg(string c_msg)
{
[...]
f_status.Text = c_msg; // And here is my problem!!
[...]
}
}
问题:
在我的特殊情况下,我尝试在运行我的代码时使用“status_msg”函数更改“f_status”-Lable 的文本!
虽然我在代码中的类之间传递了几次变量。 A无法弄清楚,为什么在“statushandler”中找不到这个明确的。 (只要我留在原来的“click_compute”内,不进入不同的类,就没有问题)。
我已经尝试过的:
1.) 我试图将“MyUserInterface”中的所有内容都更改为“public”,
2.) 我还尝试在 status_msg 中调用f_status,例如MyUserInterface.f_status.Text,
3.) 在“MyUserInterface.(Designer.)cs”(两者)中编写一个 Getter/Setter-Function,这是灾难性的,因为我无法再在 InitializeComponent 中定义 Label。
4.)
a.)阅读了很多关于在类之间传递变量的 Stackoverflow-Threads,这些都没有帮助,我发现的所有解决方案都在类之间工作,但在这种特殊情况下不是。
b.)看了很多 YouTube 教程,结果一样。
c.) 阅读一些关于在不同表单之间传递变量的 stackoverflow-Threds,但它们都有一个共同点,即“显示表单”是在已知变量后打开的。在我的特殊情况下,表单一直处于打开状态,无法关闭,也无法重新打开......
现在我没有主意了! 如果我没有看到一些细节,但我找不到它们,我不会感到惊讶......当有人可以帮助我时,我会非常高兴!
我的问题:
如何更改其他类的标签文本?
【问题讨论】:
-
问题是你的方法是静态的。静态方法在“类”级别工作,并且无法访问实例成员。所以去掉 static 关键字再试一次。
-
如果您说出它为什么不起作用,它会有所帮助。怎么了?您看到了什么错误?
-
@Isma:试过了:删除“static”并输入“MyUserInterface.f_status.Text = c_msg”给出了明显的错误“'MyUserInterface.f_status'由于其保护级别而无法访问。当然,我的错误,所以我将“InitalizeComponent”和“MyUserInterface.Designer.cs”中的标签声明更改为public。新错误:非静态字段、方法或属性“MyUserInterface.f_status”需要对象引用。 .. AND:由于同样的错误,我无法再在任何地方调用此函数。我会尝试 S.Akbari 写的 solition,如果那不起作用,稍后再返回。
-
@S.Akbari : 链接中的解决方案的问题是,您必须生成一个新的 Inctance 表单,这在此处是不可能的。
标签: c# winforms parameter-passing