2012-10-11 28 views
1

我有這樣的代碼:維護對結構或其他重構此代碼的方式的引用?

BigInteger lhs = new BigInteger(0); 
BigInteger rhs = new BigInteger(0); 

bool isLeftHandSide = true; 

for (int i = 0; i < txtResult.Text.Length; i++) 
{ 
    char currentCharacter = txtResult.Text[i]; 

    if (char.IsNumber(currentCharacter)) 
    { 
     char currentCharacter = txtResult.Text[i]; 

     if (isLeftHandSide) 
     { 
      lhs += (int)char.GetNumericValue(currentCharacter); 
     } 
     else 
     { 
      rhs += (int)char.GetNumericValue(currentCharacter); 
     } 
    } 
} 

我在想,如果有辦法,而不是存儲到當前方的參考,這樣我可以操作這些變量,而不是和擺脫if和else語句的。我希望能夠做到這一點,而不使用不安全的代碼上下文。

喜歡的東西替換這樣的:

if (isLeftHandSide) 
{ 
    lhs += (int)char.GetNumericValue(currentCharacter); 
} 
else 
{ 
    rhs += (int)char.GetNumericValue(currentCharacter); 
} 

利用該:

currentSide += (int)char.GetNumericValue(currentCharacter); 

哪裏currentSide是要麼LHS或RHS的參考。因爲它們是結構體,所以我不確定如何保留對它的引用而不是僅僅複製數據。

謝謝。

+1

你必須添加上下文的方法和循環。 –

+1

你可以在代碼片段中加入更多的上下文嗎? – Bobson

+0

增加了一些更多的上下文。 –

回答

1

你可以捕捉你的拉姆達想要的變量,像這樣:

Action<int> addToCurrentSide; 

BigInteger lhs = new BigInteger(0); 
BigInteger rhs = new BigInteger(0); 

addToCurrentSide = x => lhs += x; 

for (int i = 0; i < txtResult.Text.Length; i++) 
{ 
    char currentCharacter = txtResult.Text[i]; 

    if (char.IsNumber(currentCharacter)) 
    { 
     char currentCharacter = txtResult.Text[i]; 

     addToCurrentSide((int)char.GetNumericValue(currentCharacter)); 
    } 
} 

然後切換您剛重新分配的邊線addToCurrentSide

addToCurrentSide = x => rhs += x; 
+0

'if'仍然存在,你只是用文字描述它。 'addToCurrentSide = isLeftHandSide? x => lhs + = x:x => rhs + = x;' –

1

不能完全去除if,但你可以把它跳出循環:

bool isLeftHandSide = true; 

if (isLeftHandSide) 
    lhs = NewMethod(lhs, txtResult.Text); 
else 
    rhs = NewMethod(rhs, txtResult.Text); 
+0

你可以擺脫'if'。看到我的答案。 –

+1

@AndrewCooper你只消除了'if'因爲布爾值被硬編碼爲'true'。如果直到運行時才知道它,那麼你將需要相同的'if'語句。通過相同的推理,Henk的重構可以刪除'if'並且硬編碼使用'lhs'而不是'rhs',就像你想要的一樣。 – Servy

1

你可以這樣做,

var isLeftHandSide = true; 
var currentSide = new BigInteger(0); 

for (int i = 0; i < txtResult.Text.Length; i++) 
{ 
    char currentCharacter = txtResult.Text[i]; 
    if (char.IsNumber(currentCharacter)) 
     currentSide += (int)char.GetNumericValue(currentCharacter); 
} 

if (isLeftHandSide) 
    // lhs = currentSide; 
else 
    // rhs = currentSide; 
3

所有你需要的是一個包裝類來添加一個額外的間接層。 (我覺得這班有時是有用的,我把它作爲圍繞一個實用工具類)

public class Wrapper<T> 
{ 
    public T Value { get; set; } 
} 

然後使用它:

BigInteger lhs = new BigInteger(0); 
BigInteger rhs = new BigInteger(0); 
Wrapper<BigInteger> currentSide = new Wrapper<BigInteger>(); 

currentSide.Value = lhs; 

for (int i = 0; i < txtResult.Text.Length; i++) 
{ 
    char currentCharacter = txtResult.Text[i]; 

    if (char.IsNumber(currentCharacter)) 
    { 
     currentSide.Value += (int)char.GetNumericValue(currentCharacter); 
    } 
} 
+1

是的,[_「計算機科學中的所有問題都可以通過另一個層次的間接解決方案來解決__](http://en.wikipedia.org/維基/間接尋址)。我認爲這比lambda更直接。 –