Python 从 2.6 开始有一个很好的关键字,称为 with。 C#中有类似的东西吗?
相当于
using
语句
一个例子是
using (var reader = new StreamReader(path))
{
DoSomethingWith(reader);
}
限制是 using 子句作用域的变量类型必须实现
IDisposable
,并且在从关联代码块退出时调用其 Dispose()
方法。
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
声明的信息:
据我所知,使用
using
还有一个其他人没有提到的细微差别。
C# 的
using
旨在清理“非托管资源”,虽然保证会调用/处置它,但不一定保证其顺序/何时调用。
因此,如果您计划按照正确的调用顺序打开/关闭内容,则使用
using
可能会不走运。
来源: 以与创建相反的顺序处置对象?