在form1中初始化对象的数组:form {}



我从一本书(没有代码校正)中进行了练习,我必须构建一个BET模拟器。

我有一堂灵缇犬和4只狗。我想将它们放在一系列的灵缇犬中,并在代码的一开始就将他初始化,以便它们处于我形式的所有方法的范围。这是一个代码,它将更清楚:

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等。

怎么了?是否有更简单的方法来初始化这些变量,以便在所有方法的正确范围内?我试图使用"公共"并以Form1(){}声明它们,但它也不起作用...

声明的位置是正确的。尝试将作业移动到构造函数。

最新更新