C#中有类似Python的“with”的东西吗?

问题描述 投票:0回答:3

Python 从 2.6 开始有一个很好的关键字,称为 with。 C#中有类似的东西吗?

c# python exception
3个回答
23
投票

相当于

using
语句

一个例子是

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

限制是 using 子句作用域的变量类型必须实现

IDisposable
,并且在从关联代码块退出时调用其
Dispose()
方法。


9
投票

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
声明的信息:


-1
投票

据我所知,使用

using
还有一个其他人没有提到的细微差别。

C# 的

using
旨在清理“非托管资源”,虽然保证会调用/处置它,但不一定保证其顺序/何时调用。

因此,如果您计划按照正确的调用顺序打开/关闭内容,则使用

using
可能会不走运。

来源: 以与创建相反的顺序处置对象?

© www.soinside.com 2019 - 2024. All rights reserved.