コンストラクターのパラメーターが作成されたクラスである新しいクラスを作成する方法はありますか? 「this」キーワードを試しましたが、次のエラーが発生します: 「キーワード this は現在のコンテキストでは使用できません」
このコードは基本的に私がやろうとしていることです。プレーヤーには Game クラスへの参照が必要です。
class Player
{
Game referenceGame;
public Player(Game game)
{
referenceGame = game;
}
}
class Game
{
public Player player1 = new Player(this);
}
------------------------
フィールド初期化子ではこれを参照できない、それだけです。ただし、コンストラクター本体からこれを行うこともできます。そのため、Game クラスを次のように変更するだけです。
class Game
{
public Player player1;
public Game()
{
player1 = new Player(this);
}
}
(余談ですが、パブリック フィールドを使用しないことを強くお勧めしますが、それは異なります。関係ありません。)
0
------------------------
それはあなたが探しているものではありませんか?
class Player
{
Game referenceGame;
public Player(Game game)
{
referenceGame = game;
}
}
class Game
{
Player player1;
public Game()
{
player1 = new Player(this);
}
}
0