What is the purpose of Using? [duplicate]

2020-03-24 02:56发布

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";
}

6条回答
别忘想泡老子
2楼-- · 2020-03-24 03:28

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();
    }
}
查看更多
淡お忘
3楼-- · 2020-03-24 03:38

The using statement has the beneficial effect of disposing whatever is in the () when you complete the using block.

查看更多
不美不萌又怎样
4楼-- · 2020-03-24 03:42

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.

查看更多
Juvenile、少年°
5楼-- · 2020-03-24 03:43

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.

查看更多
我只想做你的唯一
6楼-- · 2020-03-24 03:46

The using statement ensures that Dispose() is called even if an exception occurs while you are calling methods on the object.

查看更多
混吃等死
7楼-- · 2020-03-24 03:51

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.

查看更多
登录 后发表回答