Python has a nice keyword since 2.6 called with . Is there something similar in C#?
The equivalent is the using
statement
An example would be
using (var reader = new StreamReader(path))
{
DoSomethingWith(reader);
}
The restriction is that the type of the variable scoped by the using clause must implement IDisposable
and it is its Dispose()
method that gets called on exit from the associated code block.
C# has the using
statement, as mentioned in another answer and documented here:
However, it's not equivalent to Python's with
statement, in that there is no analog of the __enter__
method.
In C#:
using (var foo = new Foo()) {
// ...
// foo.Dispose() is called on exiting the block
}
In Python:
with Foo() as foo:
# foo.__enter__() called on entering the block
# ...
# foo.__exit__() called on exiting the block
More on the with
statement here:
As far as I know, there is one additional minor difference using using
that others didn't mention.
C#'s using
is meant to clean up "unmanaged resources" and while it's guaranteed will be called/disposed, its order / when it will be called isn't necessarily guaranteed.
So if you planned on Open/closing stuff in the right order in which they got called, you might be out of luck using using
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.