0

我从我的控制台应用程序中获取了这段代码,并试图让它与 GUI 一起工作。我没有正确调用这些方法还是什么?我想单击确定按钮并在 3 个标签上分别显示数字的和、差和乘积。使困惑。请帮忙。

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;

    namespace Numbers2GUI
    {
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void okButton_Click(object sender, EventArgs e)
    {
        int num1 = 5;
        int num2 = 3;

        Sum(num1, num2);
        Difference(num1, num2);
        Product(num1, num2);

    }

    public static void Sum(int num1, int num2)

    {
        addLabel.Text = ("The sum of the numbers is {0}.", num1 + num2);
    }

    public static void Difference(int num1, int num2)
    {
        differenceLabel.Text = ("The difference of the numbers is {0}.", num1 - num2);
    }
    public static void Product(int num1, int num2)
    {
        double multiply = num1 * num2;
        productLabel.Text = ("The product of the numbers is {0}.", multiply);
    }
}

}

4

1 回答 1

3

我看到两个大问题:

  1. 使用该string.Format方法格式化标签中的结果。
  2. 如果要更新表单上的元素,Sum则不应将Difference、 和Product方法声明为。static

尝试这个:

public void Sum(int num1, int num2)
{
    addLabel.Text = string.Format("The sum of the numbers is {0}.", num1 + num2);
}

public void Difference(int num1, int num2)
{
    differenceLabel.Text = string.Format("The difference of the numbers is {0}.", num1 - num2);
}

public void Product(int num1, int num2)
{
    double multiply = num1 * num2;
    productLabel.Text = string.Format("The product of the numbers is {0}.", multiply);
}
于 2013-04-15T01:52:22.133 回答