非静态字段、方法或属性是否需要对象引用? [英] An object reference is required for the non-static field, method, or property?
问题描述
我知道这可能是一个非常新的问题,所以我深表歉意.
I know this is probably a very newbish question, so I apologize.
我正在尝试从另一个表单 MaxScore 访问 Form1 上标签的 Text 属性.
I am trying to access the Text property of a label on Form1 from another form, MaxScore.
当我单击 MaxScore 上的 Ok 按钮时,我想使用 max.ToString() 将 Form1 的 myGameCountLbl.Text 设置为 Form1 的变量 max.
When I click the Ok button on MaxScore, I want to set Form1's myGameCountLbl.Text to Form1's variable, max by using max.ToString().
这是我在 MaxScore 的 OK 按钮事件中的代码:
Here is my code in the OK button event of MaxScore:
private void okBtn_Click(object sender, EventArgs e)
{
Form1.myGameCountLbl.Text = Form1.max.ToString();
Form1.compGameCountLbl.Text = Form1.max.ToString();
}
但是当我去编译它时,我收到错误:
But when I go to compile it, I get the error:
非静态字段、方法或属性Towergame_2.Form1.myGameCountLbl"需要对象引用
An object reference is required for the non-static field, method, or property 'Towergame_2.Form1.myGameCountLbl'
Towergame_2.Form1.max 和 Towergame_2.Form1.compGameCountLbl 出现同样的错误.
I get the same error for Towergame_2.Form1.max and Towergame_2.Form1.compGameCountLbl.
不太确定如何解决这个问题.Max 是一个公共变量,两个标签也是公共变量.
Not quite sure how to fix this. Max is a public variable and the two labels are pubic as well.
谢谢!
这是我的构造函数中的代码(感谢 lassevk 的代码!):
This is the code in my constructor (thank you lassevk for the code!):
public Form1()
{
//initialize vars
myHp = 100;
compHp = 100;
youWon = 0;
compWon = 0;
money = 100;
canCompAttack = true;
gameOver = false;
//show HowToPlay Dialogue
HowToPlay howToPlay = new HowToPlay();
howToPlay.ShowDialog();
using (MaxScore maxScore = new MaxScore())
{
maxScore.MainForm = this;
maxScore.ShowDialog();
}
InitializeComponent();
}
推荐答案
Form1 是班级的名称吗?
Is by any chance Form1 the name of the class?
您需要引用表单类的实例.
You need to have a reference to an instance of the form class.
由于 okBtn
不在同一个表单上,您需要为 MaxScore
表单提供对 Form1
实例的引用.
Since okBtn
is not on the same form, you need to give the MaxScore
form a reference to the Form1
instance.
例如,您可以将其添加到您的 MaxScore
表单中:
For instance, you can add this to your MaxScore
form:
public Form1 MainForm { get; set; }
然后在您的 okBtn_Click
方法中,您将这样写:
And then in your okBtn_Click
method, you'll write this:
private void okBtn_Click(object sender, EventArgs e)
{
MainForm.myGameCountLbl.Text = MainForm.max.ToString();
MainForm.compGameCountLbl.Text = MainForm.max.ToString();
}
然后当您从 Form1
构建 MaxScore
时(我假设这就是您正在做的):
and then when you're constructing MaxScore
from Form1
(I'm assuming that's what you're doing):
using (MaxScore scoreForm = new MaxScore())
{
scoreForm.MainForm = this;
scoreForm.ShowDialog();
}
这篇关于非静态字段、方法或属性是否需要对象引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!