2015-10-18 40 views
0

我有一个包含在operationComboBox.Text中的字符串,我知道该字符串将是“+”或“ - ”。然后我就可以使用此代码执行2个方程之间的加减运算:我可以使用字符串值在C#计算中替换+或 - 运算符吗?

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语句,并直接在资金使用字符串值来进行,以缩短我的代码如何?它可能不是太重要,但我只是想我的代码很短,三个计算几乎是重复的,但对于标志。

+0

可能重复:http://stackoverflow.com/questions/13522693/c-sharp-convert-string-to-operator –

回答

4

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

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; 
+0

好主意乘以(-1)或(+1)! +1 –

+0

@YuvalItzchakov Nothing,因为 - ( - x)= + x,所以-​​1(-x)= + x。可以使用这段代码。 –

+0

它会按照它应有的方式工作。我们定义'方程[index2] .XCoeff'为-2,然后'方程式[index1] .XCoeff - (-2)==方程式[index1] .XCoeff +(-1)*(-2)' –

0

我不认为你可以因为你在你的视觉工作室书面方式代码不是编译成原始类型“字符串”。 Visual Studio将无法解释它,它只会看到你在某处放置了一些随机原始类型的“字符串”。 你最好试一下,你会发现它不会编译。

相关问题