C# using 用法

  ⑴ using 引入空间命名

 格式: using namespace 

     例如在创建C#的控制台程序时,会自动添加  

    using System;                                            using namespace
    using System.Collections.Generic;              #include <stdio>
    using System.Linq;                                     #include <math>
    using System.Text;                                      #include <string>
    using System.Threading.Tasks;                  #include<stdlib>

                (一大串啊)

   不过这样就可以直接使用命名空间中的类型,而不必指定详细的类型名称。using指令可以访问嵌套命名空间。(命名空间就是相当于C++中的头文件)

(2)创建命名空间别名

using为命名空间创建别名的用法规则为:

using alias = namespace | type;

其中namespace表示创建命名空间的别名;而type表示创建类型别名。例如,在.NET Office应用中,常常会引入Microsoft.Office.Interop.Word.dll程序集,在引入命名空间时为了避免繁琐的类型输入,我们通常为其创建别名如下:

using MSWord = Microsoft.Office.Interop.Word;

(3)资源清理

using 语句允许程序员指定使用资源的对象应当何时释放资源。using 语句中使用的对象必须实现 IDisposable 接口。此接口提供了 Dispose 方法,该方法将释放此对象的资源

代码 略

(4)支持初始化变量

using (Pen p1= new Pen(brushes.Black),p2=new Pen(brushes.blue)
{   //
}

  

//类型必须相同

 using ( IDisposable font =new Font ("vafeea e",10)pen = new Pen(Brushes.Black))

   {
   float size = (font as Font).Size;
   Brush brush = (pen as Pen).Brush;
   }
  

//类型不一定相同

 

  

 
原文地址:https://www.cnblogs.com/zykh/p/7687952.html