Python自2.6以来就有一个很好的关键字叫做 with 。 C#中有类似的东西吗?
答案 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
可能会失败。