.NET 使用块和返回;关键词

发布于 2024-08-27 04:32:15 字数 231 浏览 4 评论 0原文

当我说这个时,

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

心的憧憬 2024-09-03 04:32:15

你错了;它被处置。

using 语句编译为 try / finally 块,用于在 finally 块中处置原始对象。
finally总是执行,即使 try 块内的代码返回值或引发异常也是如此。

You are incorrect; it will be disposed.

The using statement compiles to a try / finally block that disposes the original object in the finally block.
finally blocks are always executed, even if the code inside the try block returned a value or threw an exception.

oО清风挽发oО 2024-09-03 04:32:15

using 语句将在返回值之前调用 db 对象的 Dispose

using statement will call Dispose of db object before value returning.

半衾梦 2024-09-03 04:32:15

您的 using 语句确实会成功。它类似于以下内容(C# 编译器会将 using 语句翻译为:

Entities db = new Entities();
try
{
    return db.TableName.AsQueryable().ToList();
}
finally
{
    ((IDisposable)db).Dispose();
}

Your using statement will indeed succeed. It is akin to the following (which is what the C# compiler will translate the using statement into:

Entities db = new Entities();
try
{
    return db.TableName.AsQueryable().ToList();
}
finally
{
    ((IDisposable)db).Dispose();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文