Windows窗体 - 在表单加载时重置整数

时间:2017-11-08 14:43:48

标签: c# winforms integer

我的问题是在我的主类

中创建的整数
public int loadCountGold = 0;

当按钮触发另一个表单的外观时递增到

public void goldButton_Click(object sender, EventArgs e)
{
    loadCountGold += 5;
    Console.WriteLine(loadCountGold);
    GoldForm gForm = new GoldForm();
    gForm.Show();
}

没有将其递增的值转移到需要在if语句中使用的形式。

private void GoldForm_Load(object sender, EventArgs e)
{          
    //Sets the random (within reason) value for gold
    if (main.loadCountGold <= 1)//if its the firstload of the form
    {
        Console.WriteLine(main.loadCountGold);
        Random rand = new Random();
        currentGoldValue = rand.Next(1200, 1350);    
    }
}

我在打开表单之前在点处包含了一些写行,并且在问题表单中包含一些写行以查看该值发生了什么。这可以在下面看到

enter image description here

它显示了我的程序给出的输出,突出显示了我的“Main”类的输出,另一个是从问题表单生成的输出。

目的是在每次打开表单时使值递增,以便if语句中的代码仅在第一次打开表单时运行,但目前每次都在运行。 (我知道我需要更改它增加的数量)

2 个答案:

答案 0 :(得分:1)

在您的主要表单中,拨打GoldForm,如下所示:

GoldForm gForm = new GoldForm(this);

GoldForm的构造函数中,这样做:

Main main;
public GoldForm(Main main)
{
    InitializeComponent();
    this.main = main;
}

现在,每次点击按钮都不会创建Main的新实例。

点击3次按钮后输出:

5
10
15

答案 1 :(得分:0)

这是一个需要静态变量的问题,而不是一个实例的类。简单的答案是将整数声明更改为:

public static int loadCountGold = 0;

现在对这个变量的所有引用都指向同一个东西。

我应该指定您在后面的表单中的引用需要是Main,并带有大写字母M.

if (Main.loadCountGold <= 1)//if its the firstload of the form