无法访问公共类属性

我正在尝试创建一个应该在其代码中包含这些变量的新类:

class Map { // Variable declaration public int Width { get; set; } // Width of map in tiles public int Height { get; set; } // Height of map in tiles public int TileWidth { get; set; } public int TileHeight { get; set; } } 

但出于某种原因,在Game1.cs中创建一个新的Map类后,我似乎无法解决诸如Width和Height之类的问题。

 public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; public static SpriteBatch spriteBatch; // etc... // Class initialization Map map = new Map(); map.Width = 10; // Won't work, says it is a 'field' but used like a 'type' } 

我想我不是要设置正确的财产,但我不确定如何实际这样做。

尝试上述操作时,我收到两条错误消息:

‘Deep.Game1.Map’是一个’字段’,但像’类型’一样使用

类,结构或接口成员声明中的标记’=’无效

您尚未将该代码放在可执行代码块中。 你不能只在一个类型内部浮动一个属性设置器; 它需要在方法,构造函数等内部。

如果要在初始化字段时设置宽度,则可以使用对象初始值设定项语法:

 private Map map = new Map() {Width = 10}; 

这有效:

 void Main() { Map map = new Map(); map.Width = 10; } class Map { public int Width { get; set; } // Width of map in tiles public int Height { get; set; } // Height of map in tiles public int TileWidth { get; set; } public int TileHeight { get; set; } } 

也许你有一个失踪; 或者在某个地方。

我无法确定,但看起来你可能正试图在方法之外设置属性。 试试这个:

 class Game1 { Map map = new Map(); public Game1() { map.Width = 10; } } 

是否在函数内设置Width属性的代码? 它需要。 如果不是你会看到这个错误。

还不确定这条线是否输入正确,但它缺少一个分号:

  map.Width = 10