三种不一样的C# using做用,令using关键字在.NET程序开发过程当中占有重要的地位,特别是进行命名空间或建立别名时。sql
C# using做用,微软MSDN上解释总共有三种用途:数据库
一、引用命名空间。二、为命名空间或类型建立别名。三、使用using语句。ide
一、引用命名空间,这样就能够直接在程序中引用命名空间的类型而没必要指定详细的命名空间。函数
这个就不用说了吧,好比你们最经常使用的:usingSystem.Text;this
二、为命名空间或类型建立别名:spa
当同一个cs引用了不一样的命名空间,但这些命名控件都包括了一个相同名字的类型的时候,可使用using关键字来建立别名,这样会使代码更简洁。注意:并非说两个名字重复,给其中一个用了别名,另一个就不须要用别名了,若是两个都要使用,则两个都须要用using来定义别名的。
xml
- usingSystem;
- usingaClass=NameSpace1.MyClass;
- usingbClass=NameSpace2.MyClass;
- ......
- //使用方式
- aClassmy1=newaClass();
- Console.WriteLine(my1);
- bClassmy2=newbClass();
- Console.WriteLine(my2);
三、使用using语句,定义一个范围,在范围结束时处理对象。(不过该对象必须实现了IDisposable接口)。其功能和try,catch,Finally彻底相同。
好比:
对象
- using(SqlConnectioncn=newSqlConnection(SqlConnectionString)){......}//数据库链接
- using(SqlDataReaderdr=db.GetDataReader(sql)){......}//DataReader
PS:这里SqlConnection和SqlDataReader对象都默认实现了IDisposable接口,若是是本身写的类,那就要本身手动来实现IDisposable接口。好比:
接口
- using(Employeeemp=newEmployee(userCode))
- {
- ......
- }
- Emlpoyee.cs类:
- publicclassEmployee:IDisposable
- {
- 实现IDisposable接口#region实现IDisposable接口
- /**////
- ///经过实现IDisposable接口释放资源
- ///
- publicvoidDispose()
- {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
- /**////
- ///释放资源实现
- ///
- ///
- protectedvirtualvoidDispose(booldisposing)
- {
- if(!m_disposed)
- {
- if(disposing)
- {
- //Releasemanagedresources
- if(db!=null)
- this.db.Dispose();
- if(dt!=null)
- this.dt.Dispose();
- this._CurrentPosition=null;
- this._Department=null;
- this._EmployeeCode=null;
- }
- //Releaseunmanagedresources
- m_disposed=true;
- }
- }
- /**////
- ///析构函数
- ///
- ~Employee()
- {
- Dispose(false);
- }
- privateboolm_disposed;
- #endregion
- }
使用using语句须要注意的几点:seo
3.一、对象必须实现IDisposeable接口,这个已经说过,若是没有实现编译器会报错误。
如:
- using(stringstrMsg="MyTest")
- {
- Debug.WriteLine(strMsg);//Can'tbecompiled
- }
3.二、第二个using对象检查是静态类型检查,并不支持运行时类型检查,所以以下形式也会出现编译错误。
- SqlConnectionsqlConn=newSqlConnection(yourConnectionString);
- objectobjConn=sqlConn;
- using(objConn)
- {
- Debug .WriteLine(objConn.ToString());//Can'tbecompiled
}
不过对于后者,能够经过“as”来进行类型转换方式来改进。
- SqlConnectionsqlConn=newSqlConnection(yourConnectionString);
- objectobjConn=sqlConn;
- using(objConnasIDisposable)
- {
- Debug.WriteLine(objConn.ToString());
- }
3.三、当同时须要释放多个资源时候,而且对象类型不一样,能够这样写:
- using(SqlConnectionsqlConn=newSqlConnection(yourConnectionString))
- using(SqlCommandsqlComm=newSqlCommand(yourQueryString,sqlConn))
- {
- sqlConn.Open();//Openconnection
- //OperateDBhereusing"sqlConn"
- sqlConn.Close();//Closeconnection
- }
若是对象类型相同,能够写到一块儿:
- using(FontMyFont=newFont("Arial",10.0f),MyFont2=newFont("Arial",10.0f))
- {
- //useMyFontandMyFont2
- }//compilerwillcallDisposeonMyFontandMyFont2
3.四、using关键字只是针对C#语句,对于VB等其余语言尚未对应的功能。