C#为什么要使用'using'语句?
问题描述:
过去几周,我看到人们越来越多地使用using语句。老实说,我不明白这是怎么回事:
The last couple of weeks I have seen people using more and more the using statement. And honestly, I don''t understand how this:
public string DownloadPage(string URL)
{
/* Used to handle objects better. */
using (WebClient Client = new WebClient())
{
Client.Encoding = Encoding.UTF8;
return FixXML(Client.DownloadString(URL));
}
}
不同于:
Is any different from:
public string DownloadPage(string URL)
{
/* Used to handle objects better. */
WebClient Client = new WebClient()
Client.Encoding = Encoding.UTF8;
return FixXML(Client.DownloadString(URL));
}
答
嗨..浏览此链接理解C#中的''using''语句 [ ^ ]
Hi.. Go through this link Understanding the ''using'' statement in C#[^]
当你使用时 using 语句,确保你的变量在程序结束时被正确处理。
所以变量的类你正在使用必须实现 IDisposable 接口。
因此:
When you use the using statement, you ensure that your variable will be properly disposed at the end of the procedure.
So the class of the variable you are using must implement the IDisposable interface.
Thus :
using (WebClient client = new WebClient())
{
// ...
}
严格等同于:
is strictly equivalent to :
WebClient client = new WebClient();
// ...
client.Dispose();
希望这会有所帮助。
实际上,上述情况并不完全正确:
它严格相当于:
Hope this helps.
Actually, the above is not quite correct:
It is strictly equivalent to:
{ // Define the scope for client
WebClient client;
try
{
client = new WebClient();
// ... (use of client)
}
finally
{
if (client != null)
client.Dispose();
}
} // end of scope of client
[/ EDIT]
[/EDIT]
一般情况下,它用于两个目的:
1 - 作为指令,当它用于为命名空间创建别名或导入在其他命名空间中定义的类型时。
2 - 作为声明,当它定义了一个范围,最后一个对象将被处理。
GoodLuck
Hi.Generally it is used for two purpose:
1-As a directive, when it is used to create an alias for a namespace or to import types defined in other namespaces.
2-As a statement, when it defines a scope at the end of which an object will be disposed.
GoodLuck