![](/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.