2011-10-24 48 views
0

看看下面的代碼:變量聲明的IF C#裏面

if(down == null || down.GetFace() != Face.None || down.GetFace() != Face.Partial) 
{ 
    // I called GetFace() two times 
    // How can i avoid to call it two times, and still putting inside that if 
} 

謝謝!

+0

最好還是問了一個問題,這個問題身體的一部分,而不是你的代碼示例中的註釋。人們可能會錯過它。 – Oded

回答

1

重構的方法:

private bool IsFaceNoneOrPartial(Down down) 
{ 
    var face = down.GetFace(); 

    return face != Face.None || face != Face.Partial; 
} 

// Your code is now: 
if(down == null || IsFaceNoneOrPartial(down)) 
{ 

} 
2

更容易維護和表現第一獨立空校驗作爲特例

那麼得到的結果給一個變量,並檢查它。

if(down == null) 
    // Some exceptional case .. return or throw exception 

var result = down.GetFace(); 
if(result == Face.None || result != Face.Parial) 
    // Do your code here