2016-10-22 136 views
0

我在我的程序下面的代码:C# - 我可以/应该简化/改变这段代码吗?

#region Handle 

    if(HandleLink(input)) 
     goto Handled; 
    else if(HandlePath(input)) 
     goto Handled; 
    else if(HandleGeneratedLink(input)) 
     goto Handled; 
    else ... 
    else 
     return; // Break if not handled 

#endregion 

Handled: 

我不是很满意的,因为对我来说,似乎是一个骗子在每一个第二线使用goto语句。 有没有一种常见的方式来写这样的事情,或者这是一个有效的解决方案?

+0

你可以尝试一个布尔值设置为true,只有它设置为false当案件没有处理。如果布尔值为true,则可以使用goto。 – timmyRS

回答

2

你也可以做这样的事情:

if (!HandleLink(input) && !HandlePath(input) && !HandleGeneratedLink(input)) { 
    return; 
} 
// put the code related to "Handled" here 
+0

谢谢。我最喜欢这个答案,因为它占用了最少的空间,而且我不必在我的其他代码中分割动作(if/else)。 –

0

试试这个

if(HandleLink(input) || HandlePath(input) || HandleGeneratedLink(input)) 
goto Handled; 
else 
return; 
1

你可以做这样的事情:

if (HandleLink(input) || HandlePath(input) || HandleGeneratedLink(input)) { 
    // put the code below the "Handled" label here 
} else { 
    return; 
} 

由于||评估只在左操作数是假的正确操作,HandlePath()不会被调用时HandleLink()回报真正。它的工作原理就像您的if...else if声明!

或者,您可以创建一个名为handled变量:

var handled = false; 
if (HandleLink(input) || HandlePath(input) || HandleGeneratedLink(input)) { 
    handled = true; 
} else { 
    return; 
} 

if (handled) { 
    // move the code below the "Handled" label here. 
}