Can't access public class properties

2019-03-05 07:06发布

问题:

I'm trying to create a new class that is supposed to have these variables in its code:

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

but for some reason, after creating a new Map class in Game1.cs, I can't seem to acccess things such as Width and 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'
}

I figure I'm not trying to set the property right, but I'm not sure how to actually do so.

I get two error messages when attempting the above:

'Deep.Game1.Map' is a 'field' but used like a 'type'

and

Invalid token '=' in class, struct, or interface member declaration

回答1:

You haven't placed that code in an executable code block. You can't just have a property setter floating around inside a type; it needs to be inside a method, constructor, etc.

If you want to set the width when initializing a field then you can use the object initializer syntax:

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


回答2:

This works:

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

Maybe you have a missing ; or } somewhere.



回答3:

I can't tell for sure, but it looks like you may be trying to set the property outside of a method. Try this:

class Game1
{
    Map map = new Map();

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


回答4:

Is the code that sets the Width property inside of a function? It needs to be. If it's not you'll see this error.

Also not sure if this line was typed out correctly, but it's missing a semi-colon:

 map.Width = 10