从Windows窗体应用程序中获取值,并将它们传递回main方法

时间:2018-05-04 01:43:16

标签: c# visual-studio

我正在研究我的最终项目,而且我遇到了障碍。从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;
            }
        }

根本没有任何事情发生,它保留了原始化的原始值

1 个答案:

答案 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;
}