C#中的using语句和指令之间有什么区别? [英] What is the difference between the using statement and directive in C#?
问题描述
这基本上是一个教程问题,因为是初学者,我想在我们的C#代码开始使用的using语句(包括程序集和名称空间)之间有什么区别
this is basically a tutorial question to ask since am a beginner I would like to what is a difference between the using statement we use at start of our C# code to include assembly and namespaces
像这样:
using System.Web.Services;
,以及当我们在方法或代码内编写代码时.像这样:
and when we write inside the code within the method or code. like this:
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
有什么不同或两者相同,任何指导都会有所帮助和赞赏.
is there any difference or they both are same, any guidance would be helpful and appreciated.
推荐答案
第一个(使用指令)是将命名空间引入范围.
The first (Using Directive) is to bring a namespace into scope.
举例来说,这样您就可以写
This is for example, so you can write
StringBuilder MyStringBuilder = new StringBuilder();
而不是
System.Text.StringBuilder MyStringBuilder = new System.Text.StringBuilder();
秒(使用语句)一种用于正确使用(创建和处置)实现 IDisposable的对象界面.
The second (Using Statement) one is for correctly using (creating and disposing) an object implementing the IDisposable interface.
例如:
using (Font font1 = new Font("Arial", 10.0f))
{
byte charset = font1.GdiCharSet;
}
在这里, font 类型实现了 IDisposable
,因为它使用了当我们不再使用 Font
实例( font1
)时丢弃.
Here, the Font
type implements IDisposable
because it uses unmanaged resources that need to be correctly disposed of when we are no-longer using the Font
instance (font1
).
这篇关于C#中的using语句和指令之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!