【问题标题】:C# - Can/Should I simplify/alter this code snippet?C# - 我可以/应该简化/更改此代码片段吗?
【发布时间】:2016-10-22 06:47:25
【问题描述】:

我的程序中有以下代码:

#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 似乎是一种作弊。 有没有一种通用的方法来写这样的东西,或者这是一个有效的解决方案?

【问题讨论】:

  • 您可以尝试将布尔值设置为 true,并且仅在未处理案例时将其设置为 false。如果布尔值为真,您可以使用 goto。

标签: c# coding-style goto simplify


【解决方案1】:

你也可以这样做:

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

【讨论】:

  • 谢谢。我最喜欢这个答案,因为它占用的空间最少,而且我不必围绕我的代码的其余部分拆分操作(if/else)。
【解决方案2】:

你可以这样做:

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.
}

【讨论】:

    【解决方案3】:

    试试这个

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

    【讨论】:

      猜你喜欢
      • 2011-05-27
      • 1970-01-01
      • 2020-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-09
      • 1970-01-01
      相关资源
      最近更新 更多