我可以使用字符串值来代替c#计算中的+或-运算符吗?

本文关键字:运算符 计算 字符串 可以使 我可以 | 更新日期: 2023-09-27 18:18:16

我有一个包含在operationComboBox中的字符串。文本和我知道字符串将是"+"或"-"。然后,我可以使用以下代码在两个方程之间执行加法或减法:

if ((operationComboBox.Text == "-"))
{
    equation3XCoeff = equations[index1].XCoeff - equations[index2].XCoeff;
    equation3YCoeff = equations[index1].YCoeff - equations[index2].YCoeff;
    equation3Answer = equations[index1].Answer - equations[index2].Answer;
}
else //if (operationComboBox.Text=="+")
{
    equation3XCoeff = equations[index1].XCoeff + equations[index2].XCoeff;
    equation3YCoeff = equations[index1].YCoeff + equations[index2].YCoeff;
    equation3Answer = equations[index1].Answer + equations[index2].Answer;
}

我的问题是,我可以摆脱if语句,并使用字符串值直接在总和中执行,以便缩短我的代码在某种程度上如何?这可能不太重要,但我只是希望我的代码简短,3个计算几乎是重复的,但对于符号。

我可以使用字符串值来代替c#计算中的+或-运算符吗?

你不能直接使用它——它是一个字符串,而字符串不能代替操作符。但是基于文本,你可以初始化一些数值变量并在你的方程中使用它:

var coef = operationComboBox.Text == "-" ? -1 : 1;
equation3XCoeff = equations[index1].XCoeff + coef * equations[index2].XCoeff;
equation3YCoeff = equations[index1].YCoeff + coef * equations[index2].YCoeff;
equation3Answer = equations[index1].Answer + coef * equations[index2].Answer;

我不认为你可以,因为你在visual studio中编写的代码没有编译成基本类型'string'。Visual studio将无法解释它,它只会看到你把一些随机的基本类型'string'放在中间的地方。您最好尝试一下,您将看到它无法编译。