使用(object obj = new Object())是什么意思?

Ric*_*rdo 7 .net c# using-statement

这个陈述在C#中意味着什么?

        using (object obj = new object())
        {
            //random stuff
        }
Run Code Online (Sandbox Code Playgroud)

Jus*_*ner 13

这意味着obj工具IDisposible将在using块之后被妥善处理.它的功能与以下相同:

{
  //Assumes SomeObject implements IDisposable
  SomeObject obj = new SomeObject();
  try
  {
    // Do more stuff here.       
  }
  finally
  { 
    if (obj != null)
    {
      ((IDisposable)obj).Dispose();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 几乎是正确的,using()并不意味着一个catch语句,只有try/finally. (2认同)

Dar*_*rov 5

using (object obj = new object())
{
    //random stuff
}
Run Code Online (Sandbox Code Playgroud)

相当于:

object obj = new object();
try 
{
    // random stuff
}
finally {
   ((IDisposable)obj).Dispose();
}
Run Code Online (Sandbox Code Playgroud)