我正在研究我的最终项目,而且我遇到了障碍。从Form创建和定义的数组将被发送到Main方法,但我不能在以后进一步更改它们。
public string[] ShipTypes
{
get
{
string[] ships = new string[6];
ships[0] = "Galaxy Class";
ships[1] = "Galaxy Class";
ships[2] = "Galaxy Class";
ships[3] = "Galaxy Class";
ships[4] = "Galaxy Class";
ships[5] = "BattleCruiser";
return ships;
}
}
但是在我去改变值
之后public void verifyButton_Click(object sender, EventArgs e) {
if (shipSelected1 == birdOfPrey || shipSelected1 == battleCruiser)
{
kShips++;
if (shipSelected1 == birdOfPrey)
{
birdCount++;
ShipTypes;
ShipNames[0] = name1.Text;
ShipShields[0] = shieldValue1;
}
else
{
battleCount++;
ShipTypes[0] = battleCruiser;
ShipNames[0] = name1.Text;
ShipShields[0] = shieldValue1;
}
}
根本没有任何事情发生,它保留了原始化的原始值
答案 0 :(得分:4)
ShipTypes的get
定义保证,无论您设置该数组的值,都会返回您创建的本地ships
数组。更改您的get
。
*
访问属性时,将执行get
正文。将值传递给属性时,将执行set
正文。在ShipTypes的get
正文中,创建并返回ships
数组。你没有得到你需要的东西。
我会定义:
public string[] _shipTypes;
public string[] ShipTypes
{
get
{
if (_shipTypes == null)
{
_shipTypes = new string[6];
_shipTypes[0] = "Galaxy Class";
_shipTypes[1] = "Galaxy Class";
_shipTypes[2] = "Galaxy Class";
_shipTypes[3] = "Galaxy Class";
_shipTypes[4] = "Galaxy Class";
_shipTypes[5] = "BattleCruiser";
return _shipTypes;
}
else return _shipTypes;
}
set => _shipTypes = value;
}