问题
DUPE: Uses of "using" in C#
I have seen people use the following and I am wondering what is its purpose? Is it so the object is destroyed after its use by garbage collection?
Example:
using (Something mySomething = new Something()) {
mySomething.someProp = "Hey";
}
回答1:
Using translates, roughly, to:
Something mySomething = new Something();
try
{
something.someProp = "Hey";
}
finally
{
if(mySomething != null)
{
mySomething.Dispose();
}
}
And that's pretty much it. The purpose is to support deterministic disposal, something that C# does not have because it's a garbage collected language. The using / Disposal patterns give programmers a way to specify exactly when a type cleans up its resources.
回答2:
The using statement ensures that Dispose() is called even if an exception occurs while you are calling methods on the object.
回答3:
The using statement has the beneficial effect of disposing whatever is in the () when you complete the using block.
回答4:
You can use using when the Something
class implements IDisposable. It ensures that the object is disposed correctly even if you hit an exception inside the using
block.
ie, You don't have to manually handle potential exceptions just to call Dispose
, the using
block will do it for you automatically.
It is equivalent to this:
Something mySomething = new Something();
try
{
// this is what's inside your using block
}
finally
{
if (mySomething != null)
{
mySomething.Dispose();
}
}
回答5:
Using gets translated into
try
{
...
}
finally
{
myObj.Dispose();
}
when compiling (so in IL).
So basically you should use it with every object that implements IDisposable
.
回答6:
The 'using' block is a way to guarantee the 'dispose' method of an object is called when exiting the block.
It's useful because you might exit that block normally, because of breaks, because you returned, or because of an exception.
You can do the same thing with 'try/finally', but 'using' makes it clearer what you mean and doesn't require a variable declared outside th block.
来源:https://stackoverflow.com/questions/561354/what-is-the-purpose-of-using