当“返回”时会发生什么?从“using”内部调用堵塞?

发布于 2024-08-21 12:56:44 字数 332 浏览 4 评论 0原文

如果我有一个带有像这样的 using 块的方法...

    public IEnumerable<Person> GetPersons()
    {
        using (var context = new linqAssignmentsDataContext())
        {
            return context.Persons.Where(p => p.LastName.Contans("dahl"));
        }
    }

...从 using 块中返回值,IDisposable 对象是否仍然会被释放?

If I have a method with a using block like this...

    public IEnumerable<Person> GetPersons()
    {
        using (var context = new linqAssignmentsDataContext())
        {
            return context.Persons.Where(p => p.LastName.Contans("dahl"));
        }
    }

...that returns the value from within the using block, does the IDisposable object still get disposed?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

随波逐流 2024-08-28 12:56:44

是的,确实如此。对象的处置发生在finally 块中,即使面对返回调用,该块也会执行。它本质上扩展到以下代码

var context = new linqAssignmentsDataContext();
try {
  return context.Persons.Where(p => p.LastName.Contans("dahl"));
} finally {
  if ( context != null ) {
    context.Dispose();
  }
}

Yes it does. The disposing of the object occurs in a finally block which executes even in the face of a return call. It essentially expands out to the following code

var context = new linqAssignmentsDataContext();
try {
  return context.Persons.Where(p => p.LastName.Contans("dahl"));
} finally {
  if ( context != null ) {
    context.Dispose();
  }
}
酸甜透明夹心 2024-08-28 12:56:44

来自MSDN 文档

using 语句可确保即使在调用对象方法时发生异常,也会调用 Dispose。您可以通过将对象放入 try 块中,然后在 finally 块中调用 Dispose 来实现相同的结果;事实上,这就是编译器翻译 using 语句的方式。

所以该对象总是被释放。除非你拔掉电源线。

From the MSDN documentation:

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.

So the object is always disposed. Unless you plug out the power cable.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文