IDisposable 接口

 

提供一种用于释放非托管资源的机制。

地址:https://docs.microsoft.com/zh-cn/dotnet/api/system.idisposable?view=netframework-4.8

标题:IDisposable 接口

 

复制代码
using System;
using System.IO;
using System.Text.RegularExpressions;

public class WordCount
{
   private String filename = String.Empty;
   private int nWords = 0;
   private String pattern = @"\b\w+\b"; 

   public WordCount(string filename)
   {
      if (! File.Exists(filename))
         throw new FileNotFoundException("The file does not exist.");
      
      this.filename = filename;
      string txt = String.Empty;
      using (StreamReader sr = new StreamReader(filename)) {
         txt = sr.ReadToEnd();
      }
      nWords = Regex.Matches(txt, pattern).Count;
   }
   
   public string FullName
   { get { return filename; } }
   
   public string Name
   { get { return Path.GetFileName(filename); } }
   
   public int Count 
   { get { return nWords; } }
}
复制代码

using语句实际上是语法上的便利。 在编译时, 语言编译器将为try / finally块实现中间语言 (IL)。

有关using语句的详细信息, 请参阅using 语句using 语句主题。

 

Try/Finally 块

如果编程语言不支持像或using Visual Basic 中C#的语句这样的构造, 或者不想使用它, IDisposable.Dispose则可以从finally try /语句。 finally 下面的示例将上using一示例try / finally中的块替换为块。

复制代码
using System;
using System.IO;
using System.Text.RegularExpressions;

public class WordCount
{
   private String filename = String.Empty;
   private int nWords = 0;
   private String pattern = @"\b\w+\b"; 

   public WordCount(string filename)
   {
      if (! File.Exists(filename))
         throw new FileNotFoundException("The file does not exist.");
      
      this.filename = filename;
      string txt = String.Empty;
      StreamReader sr = null;
      try {
         sr = new StreamReader(filename);
         txt = sr.ReadToEnd();
      }
      finally {
         if (sr != null) sr.Dispose();     
      }
      nWords = Regex.Matches(txt, pattern).Count;
   }
   
   public string FullName
   { get { return filename; } }
   
   public string Name
   { get { return Path.GetFileName(filename); } }
   
   public int Count 
   { get { return nWords; } }
}
复制代码

 

posted on   荆棘人  阅读(246)  评论(0编辑  收藏  举报

编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
历史上的今天:
2017-12-06 理解内存
2016-12-06 网络搜集-获取文件大小
2016-12-06 js获取文件大小

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示