c#中using 的作用

关键字 using 含有三种作用:

1.using 指令 。using + 命名空间名字 来引入命名空间,这样可以在程序中直接用命名空间中的类型。

2.using 别名指示符。using + 别名 = 包括详细命名空间

例如:

using System.Timers;

using System.Threading;

using MyTimer =  System.Timers.timer; // using 别名

namespance test

{

class test

{

.……

Timer timer = new Timer();

// 此时报错 “Timer”是“System.Timers.Timer” “System.Threading.Timer”之间的不明确的引用

//解决方法可以使用命名空间全称

System.Timers.Timer timer = new System.Timers.Timer();

//或using的别名 声明命名空间时如上面

MyTimer myTimer = new MyTimer();

}

}

3.定义一个范围,将在此范围之外释放一个或多个对象

场景:

当在某个代码段中使用了类的实例,而希望无论因为什么原因,只要离开了这个代码段就自动调用这个类实例的Dispose。

要达到这样的目的,用try...catch来捕捉异常也是可以的,但用using也很方便。

using(SqlConnection con == new SqlConnection())

{

//代码

}//调用 con 的 Dispose。

原文地址:https://www.cnblogs.com/yhongyu/p/2383461.html