C#为什么要使用'using'语句? [英] C# Why use the 'using' statement?

查看:100
本文介绍了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


这篇关于C#为什么要使用'using'语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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