0

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

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”是一个“字段”,但用作“类型”

类、结构或接口成员声明中的标记“=”无效

4

4 回答 4

7

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

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

private Map map = new Map() {Width = 10};
于 2013-10-22T19:06:59.493 回答
3

这有效:

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; }
}

也许你有一个失踪;}某处。

于 2013-10-22T19:06:40.357 回答
1

我不能确定,但​​看起来您可能正在尝试在方法之外设置属性。尝试这个:

class Game1
{
    Map map = new Map();

    public Game1()
    {
        map.Width = 10;
    }
}
于 2013-10-22T19:07:52.420 回答
0

是在函数内部设置Width属性的代码吗?它需要。如果不是,您将看到此错误。

也不确定此行是否输入正确,但缺少分号:

 map.Width = 10
于 2013-10-22T19:08:31.873 回答