C# 如何在我的 Windows 窗体应用程序中的字符串内部进行一些基本数学运算

标签 c# visual-studio-2017

所以对很多人来说,这可能看起来很简单,我通常会自己学习其中的大部分内容,但我需要一些帮助。我需要添加来自不同文本框的 2 个或更多数字的值,例如,如果有人在一个框中输入“5”,在另一个框中输入“5”,然后点击一个按钮进行计算。所以总而言之,我需要的是在需要时在字符串中完成数学运算。我可能只需要知道代码即可。从我的研究和试图找出的内容来看,我认为与 Convert.ToInt32()) 或类似的东西有关。它必须是这样的字符串:

if (textBox1.Text == string.Empty && textBox2.Text == string.Empty && textBox3.Text == string.Empty && textBox4.Text == string.Empty)
{
    MessageBox.Show("All fields are empty, try again!");
}
else if (textBox1.Text != string.Empty && textBox2.Text != string.Empty && textBox3.Text != string.Empty && textBox4.Text != string.Empty)
{
    string a = textBox1.Text;
    string b = textBox2.Text;
    string c = textBox3.Text;
    string d = textBox4.Text;

    if (txtmessagechanged != null)
        txtmessagechanged("Your total is ", null);
}

所以这是我程序中的一些示例文本,我的问题是我真正需要的是知道我输入什么来做基本的加法和减法,以及用户可以从另一个静态菜单中选择的一些百分比,例如增加 25% 或增加 5%。如果需要澄清,请告诉我,谢谢。

最佳答案

如果你事先知道什么样的值,你可以使用合适的 int.TryParse long.TryParse double.TryParse 等。如果您不确定数字的类型,请使用安全的类型 (double.TryParse)。如果您对货币方面的东西感兴趣,请使用 decimal 那么您可能正在寻找以下内容:

int parsedInt;
if(int.TryParse(textBox.Text, out parsedInt)==true){
    //Now parsedInt is a number you can do math
}
else{
    //Entered text can not be parsed :(
    //Warn user??
}

关于C# 如何在我的 Windows 窗体应用程序中的字符串内部进行一些基本数学运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45341028/

相关文章:

c# - 添加简单的 TagHelper 会导致此错误 : "RenderBody has not been called for the page "

c# - 通过OpenXML生成word文档

visual-studio - 在 Visual Studio 中隐藏 "Bottom Panel"的快捷键;无论工具窗口的数量如何

C# 是按值传递对象吗?

c# - 使用网络应用程序通过机器人主动发送消息

c++ - 带有 ftime 函数的 Visual Studio 2015/2017 年 2038 错误

windows - 为什么 Visual Studio 2017 在启动时打开 Windows "For developers"设置?

c# - 我如何阻止 visual studio 2017 在保存时构建

visual-studio - Resharper 'Ctrl + Alt Click'不适用于Visual Studio 2017

c# - DateTime.Today ,一天的开始还是结束?