冗余控制流跳转语句

时间:2014-11-03 05:33:58

标签: c#

我正在查看一些代码。 VS将return语句标记为Redundant控制流跳转语句并建议删除它。什么是正确的语法?

private async void TokenButton_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            var accountType = _settings["account_type"];

            if (accountType.Equals(AccountTypeMicrosoft))
            {
                this.Status.Text += "The original token is good for Live. No new token is needed.\n";
            }
            else
            {
                // Get access token for the target service
                if (!await GetAccessTokenForServiceAsync().ConfigureAwait(true))
                {
                    return;
                }
            }
        }
        catch (Exception ex)
        {
            this.Status.Text += "Exception caught: '" + ex.Message + "'.";
            this.Status.Foreground = _errorBrush;
        }
    }

3 个答案:

答案 0 :(得分:3)

删除整个if并将其替换为:

await GetAccessTokenForServiceAsync().ConfigureAwait(true)

您不需要检查结果,因为在任何一种情况下发生的下一件事都将是方法的结束。

答案 1 :(得分:3)

你的功能是这样的: if (condition) { return; } return; return语句是多余的。

答案 2 :(得分:0)

您可以先检查验证条件,然后再按

进行处理
  if (!await GetAccessTokenForServiceAsync().ConfigureAwait(true))
   {
       return;
   }

    try {
       var accountType = _settings["account_type"];

        if (accountType.Equals(AccountTypeMicrosoft))
        {
            this.Status.Text += "The original ... ";
        }
     }

  catch() {}