在使用指令部分时使用关键字与在类中使用关键字来调用对象上的dispose方法之间的区别? [英] Difference between using keyword when used in using directive section and when used with in a class to call the dispose method on the object ?

查看:56
本文介绍了在使用指令部分时使用关键字与在类中使用关键字来调用对象上的dispose方法之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们使用相同的键,即'using'来包含名称空间,也可以在对象上调用Dispose方法,例如......



使用System。对象;



使用(SqlConnection conn = new SqlConnection(connString))

{

...

}



我的问题是编译器如何知道使用关键字'using'的目的是什么?



我尝试了什么:



我不知道怎么试试这个怎么知道编译器会这样做。

解决方案

它是由上下文完成的。如果关键字在class \method之外,则假定您正在执行命名空间版本,如果关键字在类中,则假定它是对象dispose版本。


1。作为指令(命名空间的快捷方式):



 System.Data.SqlClient.SqlConnection myCon =  new  System.Data.SqlClient.SqlConnection(connectionString); 



为简化上述说法,请写下:

< pre lang =c#> 使用 System.Data.SqlClient;

在任何声明之前(在课程的最顶层),然后你可以将简化语句写为:

 SqlConnection myCon =  new  SqlConnection(connectionString); 



这样就可以包含SqlConnection类所需的命名空间,这样您就不必在创建SqlConnection类的对象时包含完整的命名空间。



2.作为声明(处理任何实现IDisposable接口的对象引用)



 使用(SqlC onnection myCon =  new  SqlConnection(connectionString)){
// 做的工作
}



它用于自动释放资源,但只能用于实现IDisposable的类型。


We use the same key i.e 'using' for including the name space and also to call the Dispose method on the object like...

using System.Object;
and
using (SqlConnection conn = new SqlConnection(connString))
{
...
}

My question is how the compiler will know for what purpose the keyword 'using' is used ?

What I have tried:

I do not have idea how to try this to know how the compiler will do this.

解决方案

It does it by context. If the keyword is outside of a class\method it assumes you are doing the namespace version, if the keyword is inside a class it assumes it is the object dispose version.


1. As a directive(shortcut for namespaces):

System.Data.SqlClient.SqlConnection myCon = new System.Data.SqlClient.SqlConnection(connectionString);


To simplify the above statement just write:

using System.Data.SqlClient;

before any declaration(on very top of the class) and then you may write the simplified statement as:

SqlConnection myCon = new SqlConnection(connectionString);


This way you have included the namespace required for "SqlConnection" class so that you don't have to include the complete namespace whenever you create the object of "SqlConnection" class.

2. As a statement(to dispose any object references implementing the IDisposable interface)

using(SqlConnection myCon = new SqlConnection(connectionString)){
//do the work
}


It is used to release resources automatically but can only be used with types that implement IDisposable.


这篇关于在使用指令部分时使用关键字与在类中使用关键字来调用对象上的dispose方法之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆