我在operationComboBox.Text中包含了一个字符串,并且我知道该字符串要么是"+“,要么是"-”。然后,我可以使用以下代码对两个方程执行加减操作:
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次计算几乎重复,但符号。
发布于 2015-10-18 14:46:53
您不能直接使用它--它是一个字符串,不能用字符串代替操作符。但是根据文本,您可以初始化一些数值变量并在您的方程中使用它:
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;发布于 2015-10-18 14:47:48
我不认为您可以这样做,因为您在visual中编写的代码没有编译成原始类型的“string”。Visual将无法解释它,它只会看到您将一些随机的原始类型'string‘放在不知道的地方。你最好试一试,你会发现它不会编译。
https://stackoverflow.com/questions/33199194
复制相似问题