在C#中有类似Python的'with'吗?

时间:2009-07-25 22:27:18

标签: c# python exception

Python自2.6以来就有一个很好的关键字叫做 with 。 C#中有类似的东西吗?

3 个答案:

答案 0 :(得分:24)

等效于using语句

一个例子是

  using (var reader = new StreamReader(path))
  {
    DoSomethingWith(reader);
  }

限制条件是using子句作用域的变量类型必须实现IDisposable,并且它是从关联代码块退出时调用的Dispose()方法。

答案 1 :(得分:5)

C#有using语句,如另一个答案所述,并在此处记录:

然而,它与Python的with语句不等同,因为没有__enter__方法的模拟。

在C#中:

using (var foo = new Foo()) {

    // ...

    // foo.Dispose() is called on exiting the block
}

在Python中:

with Foo() as foo:
    # foo.__enter__() called on entering the block

    # ...

    # foo.__exit__() called on exiting the block

有关此处with声明的更多信息:

答案 2 :(得分:-1)

据我所知,使用using的其他一些细微差别是其他人没有提到的。

C#' s using旨在清理"非托管资源"虽然它的保证将被调用/处理,但它的订单/何时被调用并不一定得到保证。

因此,如果您计划以正确的顺序打开/关闭内容,那么使用using可能会失败。

来源: Dispose of objects in reverse order of creation?