【问题标题】:Initializing array of objects in Form1 : Form{} [duplicate]在 Form1 中初始化对象数组:Form{} [重复]
【发布时间】: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 ... 你的赋值代码应该在构造函数中,正如其他人已经指出的那样

标签: c# arrays oop scope


【解决方案1】:

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

【讨论】:

  • 感谢所有答案,抱歉重复。在发布想法之前,我在谷歌甚至这里看了很多。好吧,可惜了,但是……我知道构造函数的概念,但以前从未使用过它们。我会看看 :) 祝你有美好的一天。
猜你喜欢
  • 2018-09-19
  • 1970-01-01
  • 2012-01-17
  • 1970-01-01
  • 2018-06-22
  • 1970-01-01
  • 2017-02-16
相关资源
最近更新 更多