2015-10-18 17 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將無法解釋它,它只會看到你在某處放置了一些隨機原始類型的「字符串」。 你最好試一下,你會發現它不會編譯。

相關問題