【发布时间】:2017-11-22 15:24:40
【问题描述】:
我从书中得到了一个练习(没有代码更正),我必须在其中构建一个投注模拟器。
我有一个灰狗班和这个班的 4 条狗。 我想把它们放在一个 Greyhound 数组中,并在代码的最开始初始化他,这样它们就在我表单的所有方法的范围内。 这是一段代码,它会更清楚:
public partial class Form1 : Form
{
Greyhound dog1 = new Greyhound();
Greyhound dog2 = new Greyhound();
Greyhound dog3 = new Greyhound();
Greyhound dog4 = new Greyhound();
Guy joe = new Guy() { name = "Joe", myBet = null, cash = 50};
Guy bob = new Guy() { name = "Bob", myBet = null, cash = 75 };
Guy al = new Guy() { name = "Al", myBet = null, cash = 45 };
Greyhound[] dogs = new Greyhound[4] { dog1, dog2, dog3, dog4 }; //Here's the problem
public Form1(){ .....
但是当我尝试初始化我的数组时,他似乎找不到 dog1、dog2 等。
怎么了? 有没有更简单的方法来初始化这些变量,以便在所有方法的正确范围内? 我尝试使用“public”并在 Form1(){} 中声明它们,但它也不起作用......
【问题讨论】:
-
“好像他找不到” - 不要给编译器错误你自己的解释,逐字研究它们。将引用其他字段的数组初始化移动到构造函数中。
-
@mituw 你把他的代码放到了一个方法中。他的代码不在方法中。无论哪种方式,这都是重复的。
-
啊,你是对的@john .. 我没注意到.. DoT ... 你的赋值代码应该在构造函数中,正如其他人已经指出的那样