2011-10-24 53 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