简体   繁体   English

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

[英]What does using(object obj = new Object()) mean?

What does this statement means in C#? 这个陈述在C#中意味着什么?

        using (object obj = new object())
        {
            //random stuff
        }

It means that obj implements IDisposible and will be properly disposed of after the using block. 这意味着obj实现了IDisposible并且在using块之后将被正确处理掉。 It's functionally the same as: 它的功能与以下相同:

{
  //Assumes SomeObject implements IDisposable
  SomeObject obj = new SomeObject();
  try
  {
    // Do more stuff here.       
  }
  finally
  { 
    if (obj != null)
    {
      ((IDisposable)obj).Dispose();
    }
  }
}
using (object obj = new object())
{
    //random stuff
}

Is equivalent to: 相当于:

object obj = new object();
try 
{
    // random stuff
}
finally {
   ((IDisposable)obj).Dispose();
}

why does it exist tho. 为什么它存在。

It exists for classes where you care about their lifetime, in particular where the class wraps a resource in the OS and you want to release it immediately. 它存在于您关心其生命周期的类中,特别是在类在操作系统中包装资源并且您希望立即释放它的情况下。 Otherwise you would have to wait for the CLR's (non deterministic) finalizers. 否则你将不得不等待CLR(非确定性)终结器。

Examples, file handles, DB connections, socket connections, .... 示例,文件句柄,数据库连接,套接字连接,....

it is a way to scope an object so the dispose method is called on exit. 它是一种范围对象的方法,因此在退出时调用dispose方法。 It is very useful for database connections in particuler. 它对于特定的数据库连接非常有用。 a compile time error will occur if the object does not implement idisposable 如果对象没有实现idisposable,将发生编译时错误

using确保在using块之后正确处理已分配的对象,即使块中发生未处理的异常也是如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM