gpt4 book ai didi

c# - 字符串值不能通过类方法赋值

转载 作者:行者123 更新时间:2023-12-02 00:27:19 25 4
gpt4 key购买 nike

您好,我的 Windows 窗体应用程序中的类变量似乎有问题。

它是我的 Player 类中的一个 string 变量。当我创建 Player 对象时,我似乎无法将 string 值分配给 playerName 变量。

我已经手动创建了 GetSet 方法,但我看不出有什么问题。

我多次收到一条消息,通知我字符串 playerName 未分配,并将保留其默认值 null。我不确定为什么会出现这种情况。

class Player
{

private string playerName = ""; //Variable used for giving each player a unique identifier, eg. 'Player One', etc


//public string PlayerName { get => playerName; set => playerName = value; }


public void setPlayerName(string name) //Sets the player's name for the game (UNSC or Covenant)
{
name = this.playerName;
}

public string getPlayerName() //Returns the player's name
{
return playerName;
}
}

创建 Player 类并尝试将 playerName 显示到文本框不起作用,playerName 值仍为 null

public partial class FrmBoardGameApp : Form
{
public FrmBoardGameApp()
{
InitializeComponent();
}

ArrayList Players = new ArrayList();

public void creationOfPlayers() //BUG!!! Values stay null
{

Player playerOne = new Player(); //Player 1
Player playerTwo = new Player(); //Player 2
playerOne.setPlayerName("Player One");
playerTwo.setPlayerName("Player Two");

Players.Add(playerOne); //Player name value is still null at this point
Players.Add(playerTwo);
}


//Here's the textbox assignment code

public bool playerTurn = true; //A bool variable used to keep track of whose turn it is
public bool setupCheck = false; // Ensures that the endturn button cannot be hit unless all setup is done
public int setupCheckValue = 0; //Ensures that the setup button can only be hit once

public void testingPlayerTurn() //A method used to test whose turn it is
{
if (setupCheck != true)
{
MessageBox.Show("Game is not setup, please setup the game");
}
else
{
//Textbox is empty, as playerName value remains null
if (playerTurn)
{
Players.ToArray();
Player firstPlayer = (Player)Players[0];
txtAns.Text = firstPlayer.getPlayerName();
/*
* This method of accessing an element and controlling/manipulating its values works
*/
}
else if (!playerTurn)
{
//playerTwo.setPlayerName(factionTwo);
//txtAns.Text = playerTwo.getPlayerName();
}
}
}


private void btnEndTurn_Click(object sender, EventArgs e) //Ends the turn of the current player
{
changePlayer();
//testingPlayerTurn();
testingPlayerNames();
}
}

我在代码示例中添加了一些处理玩家分配的方法,以防万一它有任何帮助。但问题始于 creationOfPlayers 方法和 Player 类。

最佳答案

这个:

public void setPlayerName(string name) //Sets the player's name for the game (UNSC or Covenant)
{
name = this.playerName;
}

应该是相反的:

public void setPlayerName(string name) //Sets the player's name for the game (UNSC or Covenant)
{
this.playerName = name;
}

问题:您实际上将字段的值分配给了方法的本地参数。

说明:=的左边应该是接收值的变量,右边应该是给出值的变量(或者在其他情况下是引用)。

关于c# - 字符串值不能通过类方法赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59962495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com