zoukankan      html  css  js  c++  java
  • 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 = @"w+"; 
    
       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 = @"w+"; 
    
       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; } }
    }
  • 相关阅读:
    iOS.UIKit.13.UITableView -- Simple
    iOS.UIKit.12.UICollectionView
    iOS.UIKit.11.UIPickerView
    iOS.UIKit.10.UIDatePicker
    iOS.UIKit.09.UINavigationBar
    iOS.UIKit.08.UIToolbar
    iOS.UIKit.07.UIAlertView_UIActionSheet
    iOS.UIKit.06.UIProgressView_UIActivityIndicatorView
    iOS.UIKit.05.UIScrollView
    iOS.UIKit.04.UISwitch_UISegmentedControl
  • 原文地址:https://www.cnblogs.com/Tpf386/p/11996941.html
Copyright © 2011-2022 走看看