2013-03-27 74 views
2

return語句的工作流程我毫不懷疑這個嘗試,捕捉,最後用return語句的工作流程...行爲,並最終在C#

該函數用於檢索員工離開監事視圖的信息。它工作得很好,但如果有數據發現if語句,它將返回否則塊將返回。即使兩者都得到了回報,它最終也會發表聲明。 我不知道爲什麼?

代碼片段在這裏:

List<Leave> ILeaveData.GetLeaveForSupervisorView(int userID) 
{ 
    SqlConnection con = new SqlConnection(_connectionString); 
    SqlCommand cmd = new SqlCommand("Storeprocedurename", con); 
    cmd.CommandType = CommandType.StoredProcedure; 

    cmd.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int)); 
    cmd.Parameters["@Id"].Value = userID; 

    // Get employee leave information 

    try 
    { 
     con.Open(); 
     DataSet ds = new DataSet(); 
     SqlDataAdapter adapter = new SqlDataAdapter(); 
     adapter.SelectCommand = cmd; 
     adapter.Fill(ds); 


     if (ds.Tables[0].Rows.Count > 0) 
     { 
      List<Leave> leave = new List<Leave>(); 
      for (int i = 0; i < ds.Tables[0].Rows.Count; i++) 
      { 
       leave.Add(CreateLeaveForAdminViewFromDataRow(ds.Tables[0].Rows[i])); 
      } 
      return leave; // if data found then statement return here 
     } 
     else 
     { 
      return null; // otherwise return here 
      // throw new Exception("Data Error"); 
     } 
     } 
     catch (SqlException err) 
     { 
      IErrorLog elog = new ErrorLog(_connectionString); 
      elog.LogSystemError(err); 
      throw new ApplicationException("Data Error", (Exception)err); 
     } 
     finally 
     { 
      if (con != null) 
      { 
       con.Close(); 
      } 
     } 
    } 

問候 沙瓦

+1

'finally'總是在try塊後運行。有什麼理由不希望它被執行? – 2013-03-27 13:03:40

+0

嗨瑞恩我同意你...但是,return語句終止它出現的方法的執行並將控制權返回給調用方法。這就是爲什麼即時通訊問爲什麼它不會發生在上述聲明? – Sarvaratchagan 2013-03-27 13:09:25

+0

我希望你明白我想要什麼...... – Sarvaratchagan 2013-03-27 13:10:39

回答

10

最後語句總是執行,即使發生也不例外。

http://msdn.microsoft.com/en-gb/library/zwc8s4fz(v=vs.110).aspx

通常情況下,在控制離開try語句finally塊運行的語句。正常執行,執行中斷,繼續,轉到或返回語句,或者將異常傳播到try語句之外,都可能發生控制權轉移。

+0

return語句終止它出現的方法的執行並將控制權返回給調用方法。這就是爲什麼即時通訊問爲什麼它不會發生在上述聲明? – Sarvaratchagan 2013-03-27 13:12:42

+0

@Sarrrva它發生,因爲它**總是**發生。如果你不想讓它發生,你可以創建一個'bool returned',在調用'return'之前將其設置爲true *,然後檢查if(返回)並退出finally包,返回' – Nolonar 2013-03-27 13:16:07

+0

@Davies你能解釋一下更具體的...給我,如果你有任何的鏈接... – Sarvaratchagan 2013-03-27 13:19:58

2

finally塊設計爲始終執行,無論是否拋出異常。

1

最終塊將在所有情況下執行。

+0

請閱讀CSharp的答案... – Sarvaratchagan 2013-03-27 13:17:06