C#中有类似Python的'with'吗?
Python 从 2.6 版本开始有一个很不错的关键词叫 with。在 C# 中有没有类似的东西呢?
3 个回答
-1
据我所知,使用using
还有一个小小的不同点,其他人没有提到。
C#中的using
主要是用来清理“非托管资源”,虽然它保证会被调用或释放,但具体的调用顺序和时间并不一定能保证。
所以,如果你打算按照它们被调用的顺序来打开或关闭某些东西,使用using
可能就不太合适了。
来源: 以创建的反向顺序释放对象?
9
C# 语言有一个叫做 using
的语句,之前的回答中提到过,这里也有相关的文档:
不过,C# 的 using
语句和 Python 的 with
语句并不完全相同,因为 C# 没有类似于 __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
语句的更多信息可以在这里找到:
23
等价的写法是 using
语句。
举个例子:
using (var reader = new StreamReader(path))
{
DoSomethingWith(reader);
}
需要注意的是,使用 using
的变量类型必须实现 IDisposable
接口,也就是说,它的 Dispose()
方法会在退出相关代码块时被调用。