[英]“Method must have a return type” and “return must not be followed by an object expression”
[英]Make object as an array return error “Method must have return type”
我遵循《 Head First》一書,但無法弄清楚為什么無法聲明對象數組。 系統一直在說“方法必須具有返回類型”。 我知道我可以標記每個單個對象的不同名稱,如dog1,dog2,dog3,並使用Guy類創建對象,例如,但是我只是想知道我做錯了什么,它不能是數組dog [0],dog [ 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;
}
}
}
在構造函數中聲明它們:
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();
}
問題在於,行dog[0] = new Greyhound();
是一條語句 ,而Greyhound[] dog = new Greyhound[4];
例如帶有初始化的字段聲明。
語句必須在方法中,但是對於您要執行的操作,還有另一種使用初始化器列表的方法:
Greyhound[] dog = new Greyhound[4]
{
new Greyhound(),
new Greyhound(),
new Greyhound(),
new Greyhound()
}
您不能只放這樣的代碼
Greyhound[] dog = new Greyhound[4];
dog[0] = new Greyhound();
在一個類中,它必須進入構造函數或其他方法中。
嘗試這個:
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;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.