我遵循Head First这本书,但我无法弄清楚为什么我的对象数组无法声明。系统一直说这种方法必须有返回类型'。我知道我可以标记每个单独的对象不同的名称,如dog1,dog2,dog3,并创建像Guy类一样的对象,但我只是想知道我做错了它不能是阵列狗[0 ],狗[1]等你能帮助我吗?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Guy Joe = new Guy() {Money = 50};
Guy Bob = new Guy() {Money = 75};
Guy Al = new Guy() {Money = 45};
Greyhound[] dog = new Greyhound[4];
dog[0] = new Greyhound();
}
public class Guy
{
public int Money;
}
class Greyhound
{
public int StartingPosition;
public int RaceTrackLengh;
public PictureBox MyPictureBox = null;
public Random Randomizer;
public int Location;
public bool Run()
{
Location += Randomizer.Next(5);
MyPictureBox.Left = StartingPosition + Location;
if (Location >= RaceTrackLengh)
{
TakeStartingPosition();
return true;
}
else
{
return false;
}
}
private void TakeStartingPosition()
{
Location = 0;
MyPictureBox.Left = StartingPosition;
}
}
}
答案 0 :(得分:1)
在构造函数中声明它们:
public Form1()
{
InitializeComponent();
Guy Joe = new Guy() {Money = 50};
Guy Bob = new Guy() {Money = 75};
Guy Al = new Guy() {Money = 45};
Greyhound[] dog = new Greyhound[4];
dog[0] = new Greyhound();
}
答案 1 :(得分:1)
问题是行dog[0] = new Greyhound();
是语句,而Greyhound[] dog = new Greyhound[4];
例如是带初始化的字段声明。
语句必须是方法,但是对于你想要做的事情,还有另一种使用初始化列表的方法:
Greyhound[] dog = new Greyhound[4]
{
new Greyhound(),
new Greyhound(),
new Greyhound(),
new Greyhound()
}
答案 2 :(得分:1)
你不能只是放置那样的代码
Greyhound[] dog = new Greyhound[4];
dog[0] = new Greyhound();
在一个类中,它必须进入构造函数或其他方法。
答案 3 :(得分:0)
试试这个:
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Guy Joe = new Guy() {Money = 50};
Guy Bob = new Guy() {Money = 75};
Guy Al = new Guy() {Money = 45};
Greyhound[] dog = new Greyhound[4];
dog[0] = new Greyhound();
}
}
public class Guy
{
public int Money;
}
class Greyhound
{
public int StartingPosition;
public int RaceTrackLengh;
public PictureBox MyPictureBox = null;
public Random Randomizer;
public int Location;
public bool Run()
{
Location += Randomizer.Next(5);
MyPictureBox.Left = StartingPosition + Location;
if (Location >= RaceTrackLengh)
{
TakeStartingPosition();
return true;
}
else
{
return false;
}
}
private void TakeStartingPosition()
{
Location = 0;
MyPictureBox.Left = StartingPosition;
}
}
}