0Pricing
C# Academy · 课时

IDisposable 与 using 语句

实现 IDisposable,使用 using 语句进行确定性清理,并与手动 try/finally 作对比。仅适用于 C# 6。

IDisposable 与 using 语句 是 CoddyKit 上的免费 C# Academy 课时。 这是第 3 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 C# Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 C# Academy 课程共包含 3 节课。

IDisposable 与 using 的作用

目标:确定性地释放资源。

  • 实现 IDisposable
  • 使用 using 语句(C# 6)
  • 与 try/finally 进行比较
  • 让清理操作保持简短且安全

实现 IDisposable

实现 IDisposable.Dispose 以释放资源(文件、套接字、句柄)。让它保持幂等。

using System;

// Simple disposable that tracks whether it was cleaned up
public sealed class FakeConnection : IDisposable
{
  public bool IsOpen { get; private set; }

  public FakeConnection()
  {
    IsOpen = true;
    Console.WriteLine("Open");
  }

  public void Dispose()
  {
    if (IsOpen)
    {
      IsOpen = false;
      Console.WriteLine("Close");
    }
  }
}

public class Program
{
  public static void Main(string[] args)
  {
    FakeConnection c = new FakeConnection();
    c.Dispose(); // manual cleanup
  }
}

try/finally 模式

try/finally 可以保证清理,但写法冗长且容易忘记。using 语句是它的简写形式。

using System;

public sealed class FakeConnection : IDisposable
{
  public void Dispose() { Console.WriteLine("Dispose called"); }
  public void Send(string msg) { Console.WriteLine("Send: " + msg); }
}

public class Program
{
  public static void Main(string[] args)
  {
    // Manual try/finally
    FakeConnection a = null;
    try
    {
      a = new FakeConnection();
      a.Send("A");
      throw new Exception("boom");
    }
    finally
    {
      if (a != null) a.Dispose(); // runs even on exception
    }

    // unreachable due to thrown exception in this demo
  }
}

using 语句演示

using 语句会包装一个隐藏的 try/finally;代码块结束时会调用 Dispose。

using System;

public sealed class FakeConnection : IDisposable
{
  public void Dispose() { Console.WriteLine("Dispose called"); }
  public void Work() { Console.WriteLine("Working"); }
}

public class Program
{
  public static void Main(string[] args)
  {
    try
    {
      using (FakeConnection c = new FakeConnection())
      {
        c.Work();
        throw new InvalidOperationException("oops");
      } // Dispose runs here automatically
    }
    catch (Exception)
    {
      Console.WriteLine("Handled");
    }
  }
}

使用 using 执行输入输出

大多数输入输出类型都实现了 IDisposable。使用 using,以便及时关闭句柄。

using System;
using System.IO;

public class Program
{
  public static void Main(string[] args)
  {
    // Create a small temp file then read it
    string path = "demo.txt";
    File.WriteAllText(path, "hello");

    using (StreamReader r = new StreamReader(path))
    {
      string text = r.ReadToEnd();
      Console.WriteLine(text);
    } // r.Dispose() closes the file handle
  }
}

using 的提示与常见陷阱

提示:

  • 优先使用 using,而不是手动调用 Dispose。
  • 让 Dispose 保持简短且安全(如果可能,不要抛出异常)。
  • 对象释放后不要再使用它们。
  • 对于多个资源,请嵌套 using 代码块以控制顺序。

using 语句的保证

快速检查:对于 IDisposable 对象,using 语句能够保证什么?

总结

总结:为资源实现 IDisposable,并将使用过程包装在 using 代码块中,从而在 C# 6 中通过隐藏的 try/finally 确保清理。

常见问题解答

「IDisposable 与 using 语句」课时是免费的吗?

是的 — 「IDisposable 与 using 语句」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 C# Academy 课程的其余内容,请升级到 CoddyKit PRO。 C# Academy 课程共包含 3 节课。

「IDisposable 与 using 语句」这节课中我会学到什么?

实现 IDisposable,使用 using 语句进行确定性清理,并与手动 try/finally 作对比。仅适用于 C# 6。 你通过在浏览器中直接运行的动手代码来练习 C# Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 C# Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 C# Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 3 节。

「IDisposable 与 using 语句」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 C# Academy 课中编写并运行代码吗?

能。每节 C# Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. try/catch/finally、throw new 与重新抛出
  2. 自定义异常与错误设计
  3. IDisposable 与 using 语句
← 返回 C# Academy