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

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hacker News: Front Page
P
Palo Alto Networks Blog
T
ThreatConnect
Apple Machine Learning Research
Apple Machine Learning Research
博客园_首页
T
True Tiger Recordings
P
Privacy & Cybersecurity Law Blog
B
Blog
IT之家
IT之家
Last Week in AI
Last Week in AI
F
Full Disclosure
Hacker News: Ask HN
Hacker News: Ask HN
C
Comments on: Blog
Microsoft Azure Blog
Microsoft Azure Blog
C
Cybersecurity and Infrastructure Security Agency CISA
Microsoft Security Blog
Microsoft Security Blog
博客园 - 【当耐特】
N
News and Events Feed by Topic
NISL@THU
NISL@THU
腾讯CDC
雷峰网
雷峰网
Security Latest
Security Latest
李成银的技术随笔
M
Microsoft Research Blog - Microsoft Research
L
LangChain Blog
L
Lohrmann on Cybersecurity
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
Check Point Blog
Y
Y Combinator Blog
Recent Announcements
Recent Announcements
博客园 - Franky
N
News | PayPal Newsroom
V
V2EX
A
About on SuperTechFans
The Register - Security
The Register - Security
月光博客
月光博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google Online Security Blog
Google Online Security Blog
MyScale Blog
MyScale Blog
Cisco Talos Blog
Cisco Talos Blog
Vercel News
Vercel News
WordPress大学
WordPress大学
C
Cyber Attacks, Cyber Crime and Cyber Security
The Hacker News
The Hacker News
IntelliJ IDEA : IntelliJ IDEA – the Leading IDE for Professional Development in Java and Kotlin | The JetBrains Blog
IntelliJ IDEA : IntelliJ IDEA – the Leading IDE for Professional Development in Java and Kotlin | The JetBrains Blog
爱范儿
爱范儿
A
Arctic Wolf
L
LINUX DO - 最新话题
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More

博客园 - 刺猬博客

利用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:本文章属个人学习总结,部分内容参考互联网上的相关文章。 其中如果发现个人总结有不正确的认知或遗漏的地方请评论告知,欢迎交流。