【问题标题】:How can i pass the value (string) of a text box to a constructor in C#?如何将文本框的值(字符串)传递给 C# 中的构造函数?
【发布时间】:2014-04-03 00:15:24
【问题描述】:

对于下面的程序,我假设创建一个类WComplex 对复数执行操作。我做到了,它工作得很好。另外,我必须创建一个带有 3 个文本框 (value1,value2,result)、4 个操作按钮 (+,-,*,/) 的简单计算器的 Windows 窗体应用程序。这使用WComplex 类(通过将其添加为新的现有项目)。

我在下面的代码中遇到的问题,例如我试图将第一个文本框中的数字(值 1)传递给 num1(所以我执行操作)如下:WComplex num1 = new WComplex(textBox1.Text);我收到一个错误,WComplex 需要两个参数(实数,虚数)。但是如何从文本框 (value 1) 中读取表单 (a+bi) 的值并将其拆分为 2 个参数或值?另外,我必须向每个特定的按钮单击添加什么代码,使其执行指定的操作?要求对下面的 cmets 进行任何澄清。

**[update] - 所以我已经弄清楚如何使用 split 和 separator 传递这两个值,请参见下面的 button1_click(添加),但我仍然遇到调试错误

Using WComplexClass;

namespace WindowsFormsApplication1
{
    public partial class Calculator : Form
    {

    public Calculator()
    {
        InitializeComponent();

    }

    // ---------------------------------------------------------------------------
   // ---------------------------------------------------------------------------

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        //text box (value 1)
    }

    private void textBox2_TextChanged(object sender, EventArgs e)
    {
        //text box (value 2)
    } 

    private void textBox3_TextChanged(object sender, EventArgs e)
    {
        //text box (result)

    }

    private double button1_Click(object sender, EventArgs e)
    {
        //addition

         string t = textBox1.Text;
        string[] split = t.Split('+');

        double num1 = Double.Parse(split[0]);
        double num2 = Double.Parse(split[1]);

        string t2 = textBox1.Text;
        string[] split2 = t2.Split('+');

        double num3 = Double.Parse(split2[0]);
        double num4 = Double.Parse(split2[1]);

        WComplex num5 = new WComplex(num1,num2);
        WComplex num6 = new WComplex(num3,num4);

        WComplex sum = num5 + num6;
    } 

    private void button2_Click(object sender, EventArgs e)
    {
        //subtraction


    }

    private void button3_Click(object sender, EventArgs e)
    {
        //multiplication


    } 

    private void button4_Click(object sender, EventArgs e)
    {
        //division

    }

    private void Calculator_Load(object sender, EventArgs e)
    {

    }

}
}

【问题讨论】:

  • 它是一个项目,我明天要参加考试,它使用了窗口窗体应用程序的一些概念(我对 OOP 和 C# 有点陌生)
  • 更新后出现的错误是什么?将其编辑到问题中。
  • 其实我只是让它工作,但它正在做随机操作。我必须弄清楚
  • 祝你好运听起来你已经掌握了窍门 :)
  • 它是在做乘法而不是加法

标签: c# winforms calculator


【解决方案1】:

您几乎回答了自己的问题。如果用户在 TextBox 中输入类似“a+bi”的内容,那么您可以使用 String.Split 在“+”上拆分它。您还应该验证和解析数据,以便可以将 int 值传递给构造函数,而不是 string 值,它可以是任何文本。

【讨论】:

  • 在这种情况下我将如何使用 string.split ? WComplex num1 = 新 WComplex(textBox1.Text); WComplex num2 = 新 WComplex(textBox3.Text); WComplex sum = num1 + num2;
  • 我解决了你的概念,我得到了它的工作,但是如果用户以 (a-bi) 的形式输入值,我是否必须添加另一个分隔符 (-) ?跨度>
猜你喜欢
  • 1970-01-01
  • 2013-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 2018-05-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多