深入C#学习系列二:不可小瞧的using关键字
来源:互联网 发布:日剧推荐 知乎 编辑:程序博客网 时间:2024/06/06 19:23
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类:
使用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等其他语言还没有对应的功能
- 深入C#学习系列二:不可小瞧的using关键字
- 深入C#学习系列二:不可小瞧的using关键字[转]
- C#之不可小瞧的using关键字
- 不可小瞧的GetHashCode函数
- c# using 关键字的用法
- c# using 关键字的用法
- c# using 关键字的用法
- Linux中不可小瞧且习以为常的安装服务方式!
- LINQ To SQL深入学习系列之二(C#3.0为LINQ的加强之二)
- C#回顾学习笔记二十七:using的两个作用
- [C++再学习系列] 深入extern关键字
- C#中using关键字的使用介绍
- C#中using关键字的使用介绍
- C#中using关键字的作用
- C#中using 关键字的多种用途
- C#关键字using的几种用法
- C#中using关键字的使用
- C#关键字using的几种用法
- OGNL, JSTL, STRUTS2标签中符号#,$,%的用法示例
- Cargo: 部署应用到Tomcat
- vc,编译命令集
- [性能]优化的七个方面
- 电压增益分贝表
- 深入C#学习系列二:不可小瞧的using关键字
- android自定义Toast视图
- SqlHelper
- 为什么说 Git 将取代 SVN 做软件版本控制?
- 用Mathematica给宝宝起名字
- 不能在 INSERT-EXEC 语句内部使用 ROLLBACK 语句 的解决办法
- 架构师书单[zz]
- 不重启Windows更改IP地址的多种实现
- 解决VS中Shockwave Flash Object不能引入,未注册问题