【问题标题】:cannot implicity convert type 'string' to 'double'无法将类型“字符串”隐式转换为“双精度”
【发布时间】:2017-05-31 21:23:58
【问题描述】:

所以我在这里解释一下这个问题: 有 3 个文本框,我们应该在其中的两个中输入一些要添加的数字,第三个应该显示这两个数字的总和。

错误: 不能将类型'string'隐式转换为'double'

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

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

    private void button1_Click(object sender, EventArgs e)
    {
        double nr1 = Convert.ToDouble(textBox1.Text);
        double nr2 = Convert.ToDouble(textBox2.Text);
        double nr3 = nr1 + nr2;
        string shfaq = Convert.ToString(nr3);
        textBox3.Text = shfaq;
    }
}
}

我想不通

【问题讨论】:

  • 错误告诉你到底是什么问题..你不知道什么..?调试代码时会发生什么..?
  • 我没有在您的代码中看到错误 - 它应该告诉您哪一行有错误?
  • 提示 - 使用调试器检查 textBox1.TexttextBox2.Text 的值。迟早你应该学习如何使用调试器。那么为什么不现在就开始学习呢?
  • 我知道问题出在哪里,但我不知道该怎么做才能解决它。
  • +1 到 @SergeyBerezovskiy - 我同意,您应该尝试并学习使用此处的调试器来调查这些值。

标签: c#


【解决方案1】:

在处理可以为 null 或空的文本框时,我发现最好使用 TryParse 系列进行转换。

private void button1_Click(object sender, EventArgs e) {
    double nr1, nr2;

    double.TryParse(textBox1.Text, out nr1);
    double.TryParse(textBox2.Text, out nr2);
    double nr3 = nr1 + nr2;
    string shfaq = nr3.ToString();
    textBox3.Text = shfaq;
}

【讨论】:

  • 不客气。请考虑将问题标记为已回答
【解决方案2】:

您可以使用double.TryParse 进行转换。 TryParse 接受一个字符串输入和一个双精度 out 参数,如果它通过,它将包含转换后的值。 TryParse 如果转换失败,则返回 false,因此您可以检查它并在失败时执行不同的操作:

private void button1_Click(object sender, EventArgs e)
{
    double nr1;
    double nr2;

    if (!double.TryParse(textBox1.Text, out nr1))
    {
        MessageBox.Show("Please enter a valid number in textBox1");
        textBox1.Select();
        textBox1.SelectionStart = 0;
        textBox1.SelectionLength = textBox1.TextLength;
    }
    else if (!double.TryParse(textBox2.Text, out nr2))
    {
        MessageBox.Show("Please enter a valid number in textBox2");
        textBox2.Select();
        textBox2.SelectionStart = 0;
        textBox2.SelectionLength = textBox2.TextLength;
    }
    else
    {
        double nr3 = nr1 + nr2;
        textBox3.Text = nr3.ToString();
    }
}

【讨论】:

    猜你喜欢
    • 2015-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-20
    • 2020-12-14
    • 2020-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多