18

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?

4

2 回答 2

29

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();
  }
}
于 2010-02-17T22:06:50.617 回答
7

MSDN 文档

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

所以对象总是被处理掉的。除非你拔掉电源线。

于 2010-02-17T22:08:45.697 回答