.NET 使用块和返回;关键词
当我说这个时,
using (Entities db = new Entities())
{
return db.TableName.AsQueryable().ToList();
}
我是否绕过了 using 块的功能,因为我返回了一些东西,并且该方法在退出 using 块之前退出,所以我认为 using 块将无法达到其目的并处置资源。
这是正确的吗?
When I say this
using (Entities db = new Entities())
{
return db.TableName.AsQueryable().ToList();
}
Do I by-pass the functionality of using block since I return something, and the method exits before exiting the using block, so I think the using block will not serve to its purpose and dispose the resource.
Is this correct?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你错了;它将被处置。
using
语句编译为try
/finally
块,用于在finally
块中处置原始对象。finally
块总是执行,即使try
块内的代码返回值或引发异常也是如此。You are incorrect; it will be disposed.
The
using
statement compiles to atry
/finally
block that disposes the original object in thefinally
block.finally
blocks are always executed, even if the code inside thetry
block returned a value or threw an exception.using
语句将在返回值之前调用 db 对象的Dispose
。using
statement will callDispose
of db object before value returning.您的 using 语句确实会成功。它类似于以下内容(C# 编译器会将 using 语句翻译为:
Your using statement will indeed succeed. It is akin to the following (which is what the C# compiler will translate the using statement into:
不,using 块将强制触发 Dispose 对象。
http://www.devx.com/dotnet/Article/33167
http://msdn.microsoft.com/en-us/library/ yh598w02(VS.80).aspx
Nope, the using block will force the firing of the Dispose object.
http://www.devx.com/dotnet/Article/33167
http://msdn.microsoft.com/en-us/library/yh598w02(VS.80).aspx