有没有一种方法可以创建一个新的类,构造函数的参数就是它在其中创建的类?我尝试了"this"关键字,但得到了错误:";关键字this在当前上下文中不可用";
代码基本上就是我要做的。玩家需要一个对其Game类的引用。
class Player
{
Game referenceGame;
public Player(Game game)
{
referenceGame = game;
}
}
class Game
{
public Player player1 = new Player(this);
}
不能在字段初始值设定项中引用this
,仅此而已。不过,您可以从构造函数主体中执行此操作,因此您只需要将Game
类更改为:
class Game
{
public Player player1;
public Game()
{
player1 = new Player(this);
}
}
(顺便说一句,我强烈建议不要使用公共字段,但那是另一回事。(
这不是你想要的吗?
class Player
{
Game referenceGame;
public Player(Game game)
{
referenceGame = game;
}
}
class Game
{
Player player1;
public Game()
{
player1 = new Player(this);
}
}