簡體   English   中英

帶有構造函數參數的 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM