惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
V2EX
C
Check Point Blog
博客园_首页
B
Blog
D
Docker
U
Unit 42
量子位
I
InfoQ
有赞技术团队
有赞技术团队
Martin Fowler
Martin Fowler
GbyAI
GbyAI
L
LangChain Blog
云风的 BLOG
云风的 BLOG
博客园 - Franky
美团技术团队
T
The Blog of Author Tim Ferriss
阮一峰的网络日志
阮一峰的网络日志
月光博客
月光博客
Vercel News
Vercel News
Recent Announcements
Recent Announcements
雷峰网
雷峰网
大猫的无限游戏
大猫的无限游戏
小众软件
小众软件
Google DeepMind News
Google DeepMind News

博客园 - 刺猬博客

利用javascript验证各种格式 通用高效分页存储过程代码 Asp.Net中使用水晶报表 SmartPager: a Flickr-style pager control with go-to-page popup layer Linux/UNIX 命令行大全完整版 分页存储过程 常用JS加密编码算法 安全验证码,简单加减法运算,机器无法识别的验证码 让你哈哈一下 中文汉字生成拼音 添加了代码着色的最新fckEditor 2.5.1 职场有多少IT精英透支健康和生命? 中国38%的IT从业人员靠微软生态系统生存 两个分页存储过程 仿163邮箱的alert提示,beta1.1 使用WebDeployment Project改善VS2005发布网站问题 (一) 基础 国外公司的大气与腾讯的小气 仿163信箱的alert提示,带效果预览图 用JS去掉打印的页眉页脚
不可小瞧的using关键字
刺猬博客 · 2008-02-06 · via 博客园 - 刺猬博客

using关键字,不知道的人可能对它不屑一顾,不就是用来引用命名空间吗?可是真正对using深入了解的人,你就真的不会小瞧它了。下面就听我给你一一道来using的用途和使用技巧。
    using关键字微软MSDN上解释总共有三种用途:1、引用命名空间。2、为命名空间或类型创建别名。3、使用using语句。
    1、引用命名空间,这样就可以直接在程序中引用命名空间的类型而不必指定详细的命名空间。
        这个就不用说了吧,比如大家最常用的:using System.Text;
    2、为命名空间或类型创建别名
        当同一个cs引用了不同的命名空间,但这些命名控件都包括了一个相同名字的类型的时候,可以使用using关键字来创建别名,这样会使代码更简洁。注意:并不是说两个名字重复,给其中一个用了别名,另外一个就不需要用别名了,如果两个都要使用,则两个都需要用using来定义别名的。
        using System; 
        using aClass = NameSpace1.MyClass; 
        using bClass = NameSpace2.MyClass;
        ......
        //使用方式
        aClass my1 = new aClass();             
        Console.WriteLine(my1); 
        bClass my2 = new bClass(); 
        Console.WriteLine(my2); 
    3、使用using语句,定义一个范围,在范围结束时处理对象。(不过该对象必须实现了IDisposable接口)。其功能和try ,catch,Finally完全相同。
        比如:
        using (SqlConnection cn = new SqlConnection(SqlConnectionString)){......}//数据库连接
        using (SqlDataReader dr = db.GetDataReader(sql)){......}//DataReader
        PS:这里SqlConnection和SqlDataReader对象都默认实现了IDisposable接口,如果是自己写的类,那就要自己手动来实现IDisposable接口。比如:
        using (Employee emp = new Employee(userCode))
        {
            ......
        }
        Emlpoyee.cs类:

public class Employee:IDisposable
{

       
#region 实现IDisposable接口
        
/// <summary>
       
/// 通过实现IDisposable接口释放资源
        
/// </summary>

        public void Dispose()
        
{
            Dispose(
true);
            GC.SuppressFinalize(
this);
        }

        
/// <summary>
        
/// 释放资源实现
         
/// </summary>
        
/// <param name="disposing"></param>

        protected virtual void Dispose(bool disposing)
        
{
            
if (!m_disposed)
            
{
                
if (disposing)
                
{
                    
// Release managed resources
                    if(db!=null)
                        
this.db.Dispose();
                    
if(dt!=null)
                        
this.dt.Dispose();
                    
this._CurrentPosition = null;
                    
this._Department = null;
                    
this._EmployeeCode = null;
                    
                }

                
// Release unmanaged resources
                m_disposed = true;
            }

        }

        
/// <summary>
        
/// 析构函数
         
/// </summary>

        ~Employee()
        
{
            Dispose(
false);
        }

        
private bool m_disposed;

        
#endregion

}

        
        

使用using语句需要注意的几点:
        3.1、对象必须实现IDisposeable接口,这个已经说过,如果没有实现编译器会报错误。
            如:  

            using( string strMsg = "My Test" )

            {            
                Debug.WriteLine( strMsg );//Can't be compiled

            }
        3.2、第二个using对象检查是静态类型检查,并不支持运行时类型检查,因此如下形式也会出现编译错误。     
         SqlConnection sqlConn = new SqlConnection( yourConnectionString );
    
     object objConn = sqlConn;
        
using ( objConn )
        
{
            
Debug.WriteLine( objConn.ToString() );//Can't be compiled
        
}

  不过对于后者,可以通过“as”来进行类型转换方式来改进。

        SqlConnection sqlConn = new SqlConnection( yourConnectionString );

        object objConn = sqlConn;

        using ( objConn as IDisposable )

       {

         Debug.WriteLine( objConn.ToString() );

       }

        3.3、当同时需要释放多个资源时候,并且对象类型不同,可以这样写:
        using( SqlConnection sqlConn = new SqlConnection( yourConnectionString ) )

        using( SqlCommand sqlComm = new SqlCommand( yourQueryString, sqlConn ) )
        {
            sqlConn.Open();//Open connection

           //Operate DB here using "sqlConn"  

            sqlConn.Close();//Close connection
        }
        如果对象类型相同,可以写到一起:
        using (Font MyFont = new Font("Arial"10.0f), MyFont2 = new Font("Arial"10.0f))
      
{
           
// use MyFont and MyFont2
        }
   // compiler will call Dispose on MyFont and MyFont2
        3.4、using关键字只是针对C#语句,对于VB等其他语言还没有对应的功能。
        PS:本文章属个人学习总结,部分内容参考互联网上的相关文章。 其中如果发现个人总结有不正确的认知或遗漏的地方请评论告知,欢迎交流。