在Form1中初始化对象数组:Form {}

时间:2017-11-22 15:24:40

标签: c# arrays oop scope

我从书中得到了一个练习(没有代码校正),我必须建立一个投注模拟器。

我有一节Greyhound和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(){}中声明它们但它不能正常工作......

1 个答案:

答案 0 :(得分:0)

声明的地方是正确的。尝试将赋值移动到构造函数。

相关问题