繁体   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