2010-02-22 34 views
4

我正在瀏覽ASP.NET應用程序中的一些舊的C#.NET代碼,確保所有SqlConnections都使用塊封裝在中。如果我在方法中的一個using塊中返回一個值,在返回之前是否使用了對象的處理方式?

我知道使用相同嘗試/終於它在處置對象的最終無論在嘗試會發生什麼。如果我有一個返回使用內的值,即使執行離開的方法,當它返回一個方法,它還是叫.Dispose()我的對象上它的返回後在/前/?

public static SqlCommand getSqlCommand(string strSql, string strConnect){ 
    using (SqlConnection con = new SqlConnection(strConnect)) 
    { 
     con.Open(); 
     SqlCommand cmd = GetSqlCommand(); 
     cmd.Connection = con; 
     cmd.CommandText = strSql; 
     return cmd; 
    } 
} 

更新:接受的答案是一個我認爲最好的回答我的問題,但請注意,this answer抓住了這個代碼的愚蠢,我要回一個使用配置連接的命令! :P

回答

3

是的,它仍然會調用處置。

運行這個非常簡單的控制檯應用程序頂部驗證:

class Program 
    { 
     static void Main(string[] args) 
     { 
      TestMethod(); 
      Console.ReadLine(); 
     } 

     static string TestMethod() 
     { 
      using (new Me()) 
      { 
       return "Yes"; 
      } 
     } 
    } 

    class Me : IDisposable 
    { 
     #region IDisposable Members 

     public void Dispose() 
     { 
      Console.WriteLine("Disposed"); 
     } 

     #endregion 
    } 
9

是。它會處理你的對象。這實際上將導致您的代碼中的問題,因爲返回的SqlCommand取決於SqlConnection,這將在控制流返回到您的主叫處置之前的。

你可以,但是,使用委託來解決這個問題。一個很好的模式來處理,這是重寫你的方法,像這樣:

public static SqlCommand ProcessSqlCommand(string strSql, string strConnect, Action<SqlCommand> processingMethod) 
{ 
    using (SqlConnection con = new SqlConnection(strConnect)) 
    { 
     con.Open(); 
     SqlCommand cmd = GetSqlCommand(); 
     cmd.Connection = con; 
     cmd.CommandText = strSql; 
     processingMethod(cmd); 
    } 
} 

然後,您可以撥打此類似:

ProcessSqlCommand(sqlStr, connectStr, (cmd) => 
    { 
     // Process the cmd results here... 
    }); 
+0

哇,好趕上!謝謝。這種方法是不是在很多地方使用的(並且是舊的),所以我可能會只是將其刪除,並創建我需要他們的命令 – adambox 2010-02-22 18:55:58

相關問題