![](/img/trans.png)
[英]How to extract constructor's parameter from a class where it's being created/ Called ? - C#
[英]C# new class with a constructor parameter that references class it is being created in
有没有办法创建一个新类,构造函数的参数是它在其中创建的类? 我尝试了 '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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.