在 C# 中处置资源

发布于 2024-11-29 08:53:24 字数 382 浏览 4 评论 0原文

ProgressBar pBar = new ProgressBar(obj);

if(_FileRead!=false)
{
    pBar.Text = langSupport.GetMessages("123", cultureName);
    pBar.ShowDialog();
}

在此示例中,我如何处置“pBar”资源。下面我指定了 3 种方法,哪种是对象处理的最佳方法?

  1. pBar.Dispose();
  2. pBar = null;
  3. pBar.Dispose(); pBar = null;
ProgressBar pBar = new ProgressBar(obj);

if(_FileRead!=false)
{
    pBar.Text = langSupport.GetMessages("123", cultureName);
    pBar.ShowDialog();
}

In this example how I can dispose "pBar" resource. Below I have specifide 3 ways, which is the best way of object dispose?

  1. pBar.Dispose();
  2. pBar = null;
  3. pBar.Dispose();
    pBar = null;

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

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

发布评论

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

评论(2

笑红尘 2024-12-06 08:53:24

ProgressBar 的创建包装在 语句。

using(ProgressBar pBar = new ProgressBar(obj))
{
   if(_FileRead!=false)
   {
       pBar.Text = langSupport.GetMessages("123", cultureName);
       pBar.ShowDialog();
   }
}

由于它实现了 IDisposable,因此这是确保正确处置的最佳方式。

Wrap the creation of the ProgressBar in a using statement.

using(ProgressBar pBar = new ProgressBar(obj))
{
   if(_FileRead!=false)
   {
       pBar.Text = langSupport.GetMessages("123", cultureName);
       pBar.ShowDialog();
   }
}

Since it implements IDisposable, this is the best way to ensure proper disposal.

此刻的回忆 2024-12-06 08:53:24

如果它支持它,我会使用:

using(ProgressBar pBar = new ProgressBar(obj))
{
  if(_FileRead!=false)
  {
      pBar.Text = langSupport.GetMessages("123", cultureName);
      pBar.ShowDialog();
  }
}

这样,当它退出使用时,它会处理所有相关对象。

If it supports it I would use:

using(ProgressBar pBar = new ProgressBar(obj))
{
  if(_FileRead!=false)
  {
      pBar.Text = langSupport.GetMessages("123", cultureName);
      pBar.ShowDialog();
  }
}

In that way when it exits the using it disposes of all the relevant objects.

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