2013-03-27 32 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

相关问题