我在使用"Form1_Load"中声明的数组时遇到问题.我的目标是能够为数组赋值,然后从其中的某些值中减去.
该数组是一个结构数组.我想我必须在其他地方公开宣布这个数组.现在我想尝试在"Form1_load"中完成大部分操作.
我想要实现的是,如果用户点击图片,它应该更新剩余的项目数(从20开始)并将总数添加到标签.他们可以点击5个不同的图片,这是阵列需要的地方.
结构:
struct Drink
{
public string name;
public int cost;
public int numberOfDrinks = 20;
}
Run Code Online (Sandbox Code Playgroud)
加载事件:
private void Form1_Load(object sender, EventArgs e)
{
const int SIZE = 5;
Drink[] drink = new Drink[SIZE];
}
Run Code Online (Sandbox Code Playgroud)
这是一个如果点击图片会发生什么的例子:
private void picCola_Click(object sender, EventArgs e)
{
drink[0].cost = 1.5;
drink[0].name = "";
}
Run Code Online (Sandbox Code Playgroud)
当您在函数Form1_Load中声明数组饮料时,它仅变为该函数的本地.没有人能看到它.您需要将变量的范围更改为全局变量(不需要公开).
private Drink[] drink;
private void Form1_Load(object sender, EventArgs e)
{
const int SIZE = 5;
drink = new Drink[SIZE];
}
Run Code Online (Sandbox Code Playgroud)
但是,您可以在其他地方实例化它.
public partial class Form1 : Form
{
public Drink[] drinks;
public const int SIZE = 5;
private void Form1_Load( object sender, EventArgs e )
{
drinks = new Drink[ SIZE ];
}
private void picCola_Click( object sender, EventArgs e )
{
drinks[0].cost = 1.5;
drinks[0].name = "";
}
}
Run Code Online (Sandbox Code Playgroud)
您需要正确地确定对象的范围!通过声明它Form1_Load,当调用其他方法时它不存在.你必须将它放在类的作用域级别(从而使它成为类的一个字段.这样它对所有被调用的方法都是可见的Form1.作用域用花括号表示:{}.考虑以下内容:
{
int a = 7;
{
int b = 5;
{
int c = 6;
a = 1; // OK: a exists at this level
b = 2; // OK: b exists at this level
c = 3; // OK: c exists at this level
}
a = 1; // OK: a exists at this level
b = 2; // OK: b exists at this level
c = 3; // WRONG: c does not exist at this level
}
a = 1; // OK: a exists at this level
b = 2; // WRONG: b does not exist at this level
c = 3; // WRONG: c does not exist at this level
}
a = 1; // WRONG: a does not exist at this level
b = 2; // WRONG: b does not exist at this level
c = 3; // WRONG: c does not exist at this level
Run Code Online (Sandbox Code Playgroud)