2014-11-03 60 views
0

我正在查看一些代碼。 VS將返回語句標記爲冗餘控制流跳轉語句,並建議將其刪除。什麼是正確的語法?冗餘控制流跳轉語句

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

回答

2

刪除整個if並將其替換爲:

await GetAccessTokenForServiceAsync().ConfigureAwait(true) 

你並不需要檢查的結果,因爲這發生在任何一種情況下,接下來的事情將是法的結束。

+1

的同時刪除了整個事情,如果它是一個純函數調用 – 2014-11-03 05:41:10

2

你的函數做的是這樣的: if (condition) { return; } return; return語句是多餘的。

+0

我想指出的是,如果'GetAccessTokenForServiceAsync()。ConfigureAwait (真)'有副作用,那麼你仍然必須評估'病情'。 – 2014-11-03 05:42:22

0

您可以檢查驗證條件,第一,然後做處理類似

if (!await GetAccessTokenForServiceAsync().ConfigureAwait(true)) 
    { 
     return; 
    } 

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

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

    catch() {}