如果我的方法返回一个使用块中的值,并在使用前返回对象的处置? [英] If I return a value inside a using block in a method, does the using dispose of the object before the return?
问题描述
我会通过一些旧的C#.NET code在ASP.NET应用程序确保所有的 SqlConnections 包装在使用块。
I'm going through some old C#.NET code in an ASP.NET application making sure that all SqlConnections are wrapped in using blocks.
我知道使用是一样的尝试 / 最后其中,其配置的对象在最后无论在尝试。如果我有一个方法,返回在使用的值,即使执行离开的方法,当它返回时,它前/还是叫 .Dispose()我的对象中/后它的返回?
I know that using is the same as try / finally where it disposes of the object in the finally no matter what happens in the try. If I have a method that returns a value inside the using, even though execution leaves the method when it returns, does it still call .Dispose() on my object before/during/after it's returning?
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;
}
}
更新:接受的答案是一个我认为最好的回答我的问题,但需要注意的是<一href="http://stackoverflow.com/questions/2313196/if-i-return-a-value-inside-a-using-block-in-a-method-does-the-using-dispose-of-t/2313223#2313223">this回答抓住了这个code中的愚蠢,我要回使用已释放的连接的命令! :P
Update: The accepted answer is the one I think best answers my question but note that this answer caught the stupidity of this code, that I'm returning a command that uses a disposed connection! :P
推荐答案
是的,它仍然会调用处理。
Yes it will still call dispose.
运行这个非常简单的控制台应用程序前检查:
Run this very simple console application top verify:
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
}
这篇关于如果我的方法返回一个使用块中的值,并在使用前返回对象的处置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!