我如何在其类之外调用另一个方法?

时间:2018-10-03 17:27:07

标签: c#

在详细介绍之前,这是我代码的一部分:

public frmAdditionTutor()
{
    InitializeComponent();

    Random rand = new Random();
    int NumberOne = rand.Next(500) + 100;
    int NumberTwo = rand.Next(500) + 100;
    lblEquation.Text = NumberOne.ToString() + " + " + NumberTwo.ToString() + "= ?";
    int Total = NumberOne + NumberTwo;
}

private void btnSolve_Click(object sender, EventArgs e)
{
    int UsersInput;
    UsersInput = Convert.ToInt32(txtInput.Text);

    if (     == UsersInput)
    {
    }
}

我想做的是拿int Total = NumberOne + NumberTwo;并将其用到If语句的空白部分。这样,它可以读取这两个数字是否与用户输入的内容匹配。如果我在“初始化”中复制了所有代码,它将更改数字THEN检查,并且尝试使用公共方法无效。我有什么办法可以调低该Total并将其带入Button的if语句中?

1 个答案:

答案 0 :(得分:0)

将您的Total设置为全局字段属性

public partial class Form1 : Form
{
    int Total; //or "public int Total { get; set; }"
    public Form1()
    {
        InitializeComponent();

        Random rand = new Random();
        int NumberOne = rand.Next(500) + 100;
        int NumberTwo = rand.Next(500) + 100;
        lblEquation.Text = NumberOne.ToString() + " + " + NumberTwo.ToString() + "= ?";
        Total = NumberOne + NumberTwo;
    }

    private void btnSolve_Click(object sender, EventArgs e)
    {
        int UsersInput;
        UsersInput = Convert.ToInt32(txtInput.Text);


        if ( Total == UsersInput)
        {
            MessageBox.Show("Correct!");
        }
        else
        {
            MessageBox.Show("Try Again");
        }
    }
}