我已经开始了一个新的XNA项目,我有一些类之间的通信问题。从本质上讲,我正在为一款基于贴图的平台游戏奠定框架,并且现在有两个非常简单的类。
类Tile(tiles .cs)包含一个名为tileccollision的枚举和一个名为Tile的结构体。
另一个,Level(Level.cs)。每当我尝试引用TileCollision或尝试创建Tile时,它都会说它在当前上下文中不存在。
我还需要做些什么来让这两个类交谈吗?它们在相同的命名空间中,不需要添加引用,因为它们不是编译的DLL或任何东西。不知道我错过了什么。
下面是tiles .cs的代码:using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace PoriPlatformer
{
class Tile
{
// Controls the collision detection and response behavior of a tile.
enum TileCollision
{
// A passable tile is one which does not hinder player motion at all, Example: Air
Passable = 0,
// An impassible tile is one which does not allow the player to move through it at all
// It is completely solid.
Impassable = 1,
// A platform tile is one which behaves like a passable tile except when the player
// is above it. A player can jump up through the platform as well as move past it
// to the left and right, but can not fall through the top of it.
Platform = 2,
}
struct Tile
{
public Texture2D Texture;
public TileCollision Collision;
public const int Width = 40;
public const int Height = 32;
public static readonly Vector2 Size = new Vector2(Width, Height);
// Constructs a new tile
public Tile(Texture2D texture, TileCollision collision)
{
Texture = texture;
Collision = collision;
}
}
}
}
以下是Level.cs中的违规代码:
// Loads an individual tile's appearance and behavior.
private Tile LoadTile(char tileType, int x, int y)
{
switch (tileType)
{
// Blank space
case '.':
return new Tile(null, TileCollision.Passable);
// Passable platform
case '~':
return LoadTile("platform", TileCollision.Platform);
// Impassable block
case '#':
return LoadTile("block", TileCollision.Impassable);
case '_':
return LoadTile("ground", TileCollision.Impassable);
default:
throw new NotSupportedException(String.Format("Unsupported tile type character '{0}' at position {1}, {2}.", tileType, x, y));
}
}
在Level.cs中下划线部分为TileCollision
正如我在评论中所说,TileCollision
是Tile
类的成员。要访问它,您必须有一个Tile
的实例。
更好的方法是将TileCollision
的enum声明移出类,如下所示:
public enum TileCollision
{
Passable = 0,
Impassable = 1,
Platform = 2,
}
class Tile { ... }
然后,假设Level.cs在相同的命名空间中,如下语句:
return new Tile(null, TileCollision.Passable);
。
请看这篇文章。
在Tile类中定义的enum和struct的默认作用域是私有的,所以它们只能从Tile类中访问。您需要将它们更改为internal或public,以便在同一名称空间中的另一个类中可见。
TileCollision和Tile(嵌套结构体)需要是公共的,以便在类外部看到。另外,您需要首先使用外部类来引用它们:
...
return LoadTile("block", Tile.TileCollision.Impassable);
...
和
...
new Tile.Tile();
...