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

发布于 2024-08-17 19:01:32 字数 136 浏览 1 评论 0原文

这个语句在C#中意味着什么?

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

What does this statement means in C#?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

榕城若虚 2024-08-24 19:01:32

这意味着 obj 实现了 IDisposible 并将在 using 块之后被正确处理。它的功能与以下相同:

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

It means that obj implements IDisposible and will be properly disposed of after the using block. 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();
    }
  }
}
涙—继续流 2024-08-24 19:01:32
using (object obj = new object())
{
    //random stuff
}

相当于:

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

Is equivalent to:

object obj = new object();
try 
{
    // random stuff
}
finally {
   ((IDisposable)obj).Dispose();
}
无法回应 2024-08-24 19:01:32

为什么它存在呢。

它存在于您关心其生命周期的类中,特别是当类在操作系统中包装资源并且您希望立即释放它时。否则,您将不得不等待 CLR 的(非确定性)终结器。

示例,文件句柄、数据库连接、套接字连接......

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.

Examples, file handles, DB connections, socket connections, ....

甲如呢乙后呢 2024-08-24 19:01:32

这是一种确定对象范围的方法,因此在退出时调用 dispose 方法。特别是对于数据库连接非常有用。如果对象未实现 idisposable,则会发生编译时错误

it is a way to scope an object so the dispose method is called on exit. It is very useful for database connections in particuler. a compile time error will occur if the object does not implement idisposable

奢欲 2024-08-24 19:01:32

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

using ensures the allocated object is properly disposed after the using block, even when an unhandled exception occurs in the block.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文