将列表设置为方法返回值,但不能使用该方法

本文关键字:方法 但不能 返回值 列表 设置 | 更新日期: 2023-09-27 18:36:24

我正在尝试将一个新的 List 变量设置为类方法返回值的结果,有点像这样:

public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    public static SpriteBatch spriteBatch;
    // ...stuff...
    // Class initialization
    private Map map = new Map() { Width = 10, Height = 10, TileWidth = 16, TileHeight = 16 };
    // Variable declaration
    List<Vector2> blockPos = new List<Vector2>();
    blockPos = map.generateMap(); // Doesn't work
    Texture2D dirtTex;
    // ...more stuff...
}

我认为它不起作用,因为它不在方法中,我可以将其放在我的 Update() 方法中,但它运行每一帧,我只想这样做一次。

尝试上述代码会导致 3 个错误:

'Deep.Game1.blockPos' is a 'field' but is used like a 'type'
Invalid token '=' in a class, struct, or interface member declaration
'Deep.Game1.map' is a 'field' but is used like a 'type'

地图类:

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; }
    Random rnd = new Random();
    // Generate a list of Vector2 positions for blocks
    public List<Vector2> generateMap()
    {
        List<Vector2> blockLocations = new List<Vector2>();
        // For each tile in the map...
        for (int w = 0; w < Width; w++)
        {
            for (int h = 0; h < Height; h++)
            {
                // ...decide whether or not to place a tile...
                if (rnd.Next(0, 1) == 1)
                {
                    // ...and if so, add a tile at that location.
                    blockLocations.Add(new Vector2(w * TileWidth, h * TileHeight));
                }
            }
        }
        return blockLocations;
    }
}

我尝试使用构造函数,但尽管没有错误,但其中的代码似乎没有运行:

public void getPos()
{
    blockPos = map.generateMap();
}

将列表设置为方法返回值,但不能使用该方法

通过声明变量,然后在 LoadContent() 方法中将其设置为 map.generateMap() 来修复:

public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    public static SpriteBatch spriteBatch;
    // ...
    // Class initialization
    private Map map = new Map() { Width = 10, Height = 10, TileWidth = 16, TileHeight = 16 };
    // Variable declaration
    List<Vector2> blockPos = new List<Vector2>();
    Texture2D dirtTex;
    /// <summary>
    /// LoadContent will be called once per game and is the place to load
    /// all of your content.
    /// </summary>
    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);
        dirtTex = Content.Load<Texture2D>("dirt");
        blockPos = map.generateMap();
    }
    // ...
}
相关文章: