无法访问公共类属性 [英] Can't access public class properties

查看:175
本文介绍了无法访问公共类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个应该有它的代码中这些变量的一个新的类:

  Map类
{
//变量声明
公众诠释宽度{获得;组; } //宽地图瓷片
公众诠释身高{搞定;组; } //地图瓷片
公众诠释的高度TileWidth {搞定;组; }
公众诠释TileHeight {搞定;组; }
}



但由于某些原因,在Game1.cs创建一个新的地图下课,我似乎无法acccess的东西,如宽度和高度

 公共类的Game1:Microsoft.Xna.Framework.Game 
{
GraphicsDeviceManager显卡;
公共静态SpriteBatch spriteBatch;

//等等......

//初始化类
地图=新地图();

map.Width = 10; //都不行,说这是一个场,但就像一个类型
使用}

我想我不是要设置该属性的权利,但我不知道如何真正做到这一点。



我得到两个错误信息在尝试以上时:




Deep.Game1.Map'是一种'场',但用于像一个类型







无效令牌'='在课堂上,结构或接口成员声明



解决方案

您还没有放置该代码在可执行代码块。你不能只是有一个属性setter左右浮动型内; 。它需要一个方法,构造等内



如果你想设置宽度初始化一个字段,那么你可以使用对象初始化语法时:

 私人地图=新地图(){宽度= 10}; 


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

解决方案

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

这篇关于无法访问公共类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆