C#中using关键字用法

C#-using用法详解  
  
using 关键字有两个主要用途: 
  (一).作为指令,用于为命名空间创建别名或导入其他命名空间中定义的类型。   (二).作为语句,用于定义一个范围,在此范围的末尾将释放对象。  
using指令 
    ①允许在命名空间中使用类型,这样,您就不必在该命名空间中限定某个类型的使用: 
             using System.Text;              using PC.Company;     ②为命名空间或类型创建别名。 
               using MyCompany = PC.Company;       //命名空间的别名。                using Project = PC.Company.Project; //类型的别名 
    using引入命名空间,并不等于编译器编译时加载该命名空间所在的程序集,程序集的加载决定于程序中对该程序集是否存在调用操作,如果代码中不存在任何调用操作则编译器将不会加载using引入命名空间所在程序集。因此,在源文件开头,引入多个命名空间,并非加载多个程序集,不会造成“过度引用”的弊端。     创建别名的另一个重要的原因在于同一文件中引入的不同命名空间中包括了相同名称的类型,如SharpMap.Geometries.Point与System.Drawing.Point。为了避免出现名称冲突,可以通过设定别名来解决:     using SGPoint = SharpMap.Geometries.Point;     using SDPoint = System.Drawing.Point; 
    尽管我们可以通过类型全名称来加以区分,但是这显然不是最佳的解决方案。用using指令创建别名,有效的解决了这种可能的命名冲突,才是最佳的解决方案。  
using语句 
    using 语句允许程序员指定使用资源的对象应当何时释放资源。using 语句中使用的对象必须实现 IDisposable 接口。此接口提供了 Dispose 方法,该方法将释放此对象的资源。 

    ①可以在 using 语句之中声明对象。       

       Font font2 = new Font("Arial", 10.0f); 

        using (font2)       { 
          // use font2       } 
    ②可以在 using 语句之前声明对象。 
      using (Font font2 = new Font("Arial", 10.0f))       { 
          // use font2       } 
    ③可以有多个对象与 using 语句一起使用,但是必须在 using 语句内部声明这些对象。 
        using (Font font3=new Font("Arial",10.0f), font4=new Font("Arial",10.0f))       { 
          // Use font3 and font4.       }  
使用规则 
    ①using只能用于实现了IDisposable接口的类型,禁止为不支持IDisposable接口的类型使用using语句,否则会出现编译错误; 
  ②using语句适用于清理单个非托管资源的情况,而多个非托管对象的清理最好以try-finnaly来实现,因为嵌套的using语句可能存在隐藏的Bug。内层using块引发异常时,将不能释放外层using块的对象资源; 
  ③using语句支持初始化多个变量,但前提是这些变量的类型必须相同,例如: 
        using(Pen p1 = new Pen(Brushes.Black), p2 = new Pen(Brushes.Blue))       {           //       } 
    ④针对初始化对个不同类型的变量时,可以都声明为IDisposable类型,例如:         using (IDisposable font = new Font("Verdana", 12), pen = new Pen(Brushes.Black))       { 
          float size = (font as Font).Size;           Brush brush = (pen as Pen).Brush;       } 


using实质 
    在程序编译阶段,编译器会自动将using语句生成为try-finally语句,并在finally块中调用对象的Dispose方法,来清理资源。所以,using语句等效于try-finally语句,例如: 
    Font f2 = new Font("Arial", 10, FontStyle.Bold);   try   { 
      //执行文本绘制操作   }   finally   { 
      if (f2 != null) ((IDisposable)f2).Dispose();}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
using System; using System.IO; using System.Text.RegularExpressions; using System.Windows.Forms; using Microsoft.Win32; namespace MRU { public partial class FormMRU : Form { public FormMRU() { #region InitializeComponent(); ListView listViewMRU = new ListView(); listViewMRU.Dock = DockStyle.Fill; listViewMRU.HeaderStyle = ColumnHeaderStyle.None; // 隐藏列标题。 listViewMRU.View = View.Details; // 详细信息。 listViewMRU.CheckBoxes = true; // 显示复选框。 listViewMRU.Scrollable = false; // 隐藏滚动条。 listViewMRU.ShowGroups = true; // 分组显示项。 listViewMRU.BeginUpdate(); ListViewGroup pro = listViewMRU.Groups.Add("profile", "profile"); listViewMRU.Items.Add(Environment.GetFolderPath(Environment.SpecialFolder.Recent)).Group = pro; listViewMRU.Items.Add(Environment.GetFolderPath(Environment.SpecialFolder.Cookies)).Group = pro; listViewMRU.Items.Add(Path.GetTempPath()).Group = pro; listViewMRU.Items.Add(Environment.GetFolderPath(Environment.SpecialFolder.History)).Group = pro; listViewMRU.Items.Add(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache)).Group = pro; ListViewGroup reg = listViewMRU.Groups.Add("regedit", "regedit"); listViewMRU.Items.Add(@"HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\TypedURLs").Group = reg; listViewMRU.Items.Add(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRU").Group = reg; listViewMRU.Items.Add(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32").Group = reg; listViewMRU.Items.Add(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Applets\Paint").Group = reg; listViewMRU.Items.Add(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Applets\Wordpad").Group = reg; ColumnHeader column = listViewMRU.Columns.Add(""); column.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent); // 自动调整列宽。 listViewMRU.EndUpdate(); listViewMRU.ItemChecked += new ItemCheckedEventHandler(listViewMRU_ItemChecked); this.Controls.Add(listViewMRU); this.ClientSize = new System.Drawing.Size(column.Width + 8, 260); this.Text = Environment.UserName; this.AutoSizeMode = AutoSizeMode.GrowAndShrink; // 禁用手动调整大小。 this.SizeGripStyle = SizeGripStyle.Hide; // 隐藏调整大小手柄。 this.StartPosition = FormStartPosition.CenterScreen; // 在桌面居显示。 #endregion } #region ListView_ItemChecked private void listViewMRU_ItemChecked(object sender, ItemCheckedEventArgs e) { if (!e.Item.Checked) return; DirectoryInfo dir = new DirectoryInfo(e.Item.Text); switch (e.Item.Index) { case 0: case 1: foreach (FileInfo info in dir.GetFiles()) { if (Regex.IsMatch(info.Extension, @".(dat|ini)", RegexOptions.IgnoreCase)) // 指定不区分大小写的匹配。 continue; this.Text = info.Name; info.Delete(); } break; case 2: foreach (FileSystemInfo info in dir.GetFileSystemInfos()) { try { if (info is FileInfo) info.Delete(); else (info as DirectoryInfo).Delete(true); } catch { continue; } finally { this.Text = info.Name; } } break; case 3: System.Diagnostics.Process.Start(e.Item.Text); break; case 4: foreach (FileInfo info in dir.GetFiles("*.*", SearchOption.AllDirectories)) { if (Regex.IsMatch(info.Extension, @".(dat|ini)", RegexOptions.IgnoreCase)) // 指定不区分大小写的匹配。 continue; try { info.Delete(); } catch { continue; } finally { this.Text = info.Name; } } break; case 5: using (RegistryKey subKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Internet Explorer\TypedURLs")) { foreach (string mru in subKey.GetValueNames()) { subKey.DeleteValue(mru); } } break; case 6: using (RegistryKey subKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRU")) { foreach (string mru in subKey.GetValueNames()) { subKey.DeleteValue(mru); } } break; case 7: using (RegistryKey subKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32")) { foreach (string mru in subKey.GetSubKeyNames()) { subKey.DeleteSubKeyTree(mru); } } break; case 8: using (RegistryKey subKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Applets\Paint\Recent File List")) { foreach (string mru in subKey.GetValueNames()) { subKey.DeleteValue(mru); } } break; case 9: using (RegistryKey subKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Applets\Wordpad\Recent File List")) { foreach (string mru in subKey.GetValueNames()) { subKey.DeleteValue(mru); } } break; } this.Text = Environment.UserName; } #endregion } }using System; using System.IO; using System.Text.RegularExpressions; using System.Windows.Forms; using Microsoft.Win32; namespace MRU { public partial class FormMRU : Form { public FormMRU() { #region InitializeComponent(); ListView listViewMRU = new ListView(); listViewMRU.Dock = DockStyle.Fill; listViewMRU.HeaderStyle = ColumnHeaderStyle.None; // 隐藏列标题。 listViewMRU.View = View.Details; // 详细信息。 listViewMRU.CheckBoxes = true; // 显示复选框。 listViewMRU.Scrollable = false; // 隐藏滚动条。 listViewMRU.ShowGroups = true; // 分组显示项。 listViewMRU.BeginUpdate(); ListViewGroup pro = listViewMRU.Groups.Add("profile", "profile"); listViewMRU.Items.Add(Environment.GetFolderPath(Environment.SpecialFolder.Recent)).Group = pro; listViewMRU.Items.Add(Environment.GetFolderPath(Environment.SpecialFolder.Cookies)).Group = pro; listViewMRU.Items.Add(Path.GetTempPath()).Group = pro; listViewMRU.Items.Add(Environment.GetFolderPath(Environment.SpecialFolder.History)).Group = pro; listViewMRU.Items.Add(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache)).Group = pro; ListViewGroup reg = listViewMRU.Groups.Add("regedit", "regedit"); listViewMRU.Items.Add(@"HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\TypedURLs").Group = reg; listViewMRU.Items.Add(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRU").Group = reg; listViewMRU.Items.Add(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32").Group = reg; listViewMRU.Items.Add(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Applets\Paint").Group = reg; listViewMRU.Items.Add(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Applets\Wordpad").Group = reg; ColumnHeader column = listViewMRU.Columns.Add(""); column.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent); // 自动调整列宽。 listViewMRU.EndUpdate(); listViewMRU.ItemChecked += new ItemCheckedEventHandler(listViewMRU_ItemChecked); this.Controls.Add(listViewMRU); this.ClientSize = new System.Drawing.Size(column.Width + 8, 260); this.Text = Environment.UserName; this.AutoSizeMode = AutoSizeMode.GrowAndShrink; // 禁用手动调整大小。 this.SizeGripStyle = SizeGripStyle.Hide; // 隐藏调整大小手柄。 this.StartPosition = FormStartPosition.CenterScreen; // 在桌面居显示。 #endregion } #region ListView_ItemChecked private void listViewMRU_ItemChecked(object sender, ItemCheckedEventArgs e) { if (!e.Item.Checked) return; DirectoryInfo dir = new DirectoryInfo(e.Item.Text); switch (e.Item.Index) { case 0: case 1: foreach (FileInfo info in dir.GetFiles()) { if (Regex.IsMatch(info.Extension, @".(dat|ini)", RegexOptions.IgnoreCase)) // 指定不区分大小写的匹配。 continue; this.Text = info.Name; info.Delete(); } break; case 2: foreach (FileSystemInfo info in dir.GetFileSystemInfos()) { try { if (info is FileInfo) info.Delete(); else (info as DirectoryInfo).Delete(true); } catch { continue; } finally { this.Text = info.Name; } } break; case 3: System.Diagnostics.Process.Start(e.Item.Text); break; case 4: foreach (FileInfo info in dir.GetFiles("*.*", SearchOption.AllDirectories)) { if (Regex.IsMatch(info.Extension, @".(dat|ini)", RegexOptions.IgnoreCase)) // 指定不区分大小写的匹配。 continue; try { info.Delete(); } catch { continue; } finally { this.Text = info.Name; } } break; case 5: using (RegistryKey subKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Internet Explorer\TypedURLs")) { foreach (string mru in subKey.GetValueNames()) { subKey.DeleteValue(mru); } } break; case 6: using (RegistryKey subKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRU")) { foreach (string mru in subKey.GetValueNames()) { subKey.DeleteValue(mru); } } break; case 7: using (RegistryKey subKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32")) { foreach (string mru in subKey.GetSubKeyNames()) { subKey.DeleteSubKeyTree(mru); } } break; case 8: using (RegistryKey subKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Applets\Paint\Recent File List")) { foreach (string mru in subKey.GetValueNames()) { subKey.DeleteValue(mru); } } break; case 9: using (RegistryKey subKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Applets\Wordpad\Recent File List")) { foreach (string mru in subKey.GetValueNames()) { subKey.DeleteValue(mru); } } break; } this.Text = Environment.UserName; } #endregion } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值