C#“使用”块

时间:2011-01-21 16:29:18

标签: c# design-patterns stream using streamreader

我有类似下面的代码......有人在这里提到WebClient,Stream和StreamReader对象都可以从使用块中受益。两个简单的问题:

1:这个小片段看起来如何使用块?我做自己的研究没有问题,所以资源链接很好,但只是看一个例子就更快更容易了,我会从中理解它。

2:我想养成良好的编码标准的习惯,如果我对使用积木更好的原因有所了解会有所帮助...是否只是让你不必担心关闭还是有更多理由?谢谢!

WebClient client = new WebClient();
Stream stream = client.OpenRead(originGetterURL);
StreamReader reader = new StreamReader(stream);

JObject jObject = Newtonsoft.Json.Linq.JObject.Parse(reader.ReadLine());
string encryptionKey = (string)jObject["key"];
string originURL = (string)jObject["origin_url"];

stream.Close()
reader.Close()

9 个答案:

答案 0 :(得分:9)

using (var client = new WebClient())
using (var stream = client.OpenRead(originGetterURL))
using (var reader = new StreamReader(stream))
{
    var jObject = Newtonsoft.Json.Linq.JObject.Parse(reader.ReadLine());
    var encryptionKey = (string)jObject["key"];
    var originURL = (string)jObject["origin_url"];
}

或简单地说:

using (var client = new WebClient())
{
    var json = client.DownloadString(originGetterURL);
    var jObject = Newtonsoft.Json.Linq.JObject.Parse(json);
    var encryptionKey = (string)jObject["key"];
    var originURL = (string)jObject["origin_url"];
}

答案 1 :(得分:5)

using (WebClient client = new WebClient())
{
    // do work
}
  

提供方便的语法,确保正确使用IDisposable个对象。

来自MSDN: using Statement (C# Reference)


  

通常,当您使用IDisposable对象时,您应该在using语句中声明并实例化它。 using语句以正确的方式调用对象上的Dispose方法,它也是一旦调用Dispose,就会导致对象本身超出范围。在using块中,该对象是只读的,不能修改或重新分配。


  

using语句确保即使在对象上调用方法时发生异常也会调用Dispose。您可以通过将对象放在try块中然后调用Dispose来实现相同的结果。在一个最后的块;实际上,这就是编译器如何翻译using语句。

答案 2 :(得分:4)

using(WebClient client = new WebClient()) {

}

相同
WebClient client;
try {
    client = new WebClient();
} finally {
    if(client != null) {
        client.Dispose();
    }
}

使用

更容易使用

答案 3 :(得分:2)

简单:

使用*using*并不是“好习惯”,更多的是处理 要处置的对象的简短方法(语法糖)。诸如文件,数据库连接以及网络中的事情。

您可以这样做:

using(WebClient we = new WebClient))
{
//do something with 'we' here
}

这基本上只是正常使用变量we然后调用we.Dispose()进行清理的快捷方式。

语法:

using (<Any class that Implements IDisposable>)
{
//use the class
}

您应该看到的其他SO问题:
What is the relationship between the using keyword and the IDisposable interface?
using various types in a using statement (C#)

答案 4 :(得分:1)

使用{}块只需在结束括号中调用Dispose(),或者更确切地说,告诉垃圾收集器它可以处置该对象。你会像以下一样使用它:

using (WebClient client = new WebClient())
{
    Stream stream = client.OpenRead(originGetterURL); StreamReader reader = new  StreamReader(stream);

    JObject jObject = Newtonsoft.Json.Linq.JObject.Parse(reader.ReadLine()); string encryptionKey = (string)jObject["key"]; string originURL = (string)jObject["origin_url"];

    stream.Close() reader.Close()
} // 'client' instance gets disposed here

答案 5 :(得分:1)

这样的事情:

using(WebClient client = new WebClient())
using(Stream stream = client.OpenRead(originGetterURL))
StreamReader reader = new StreamReader(stream) {
  JObject jObject = Newtonsoft.Json.Linq.JObject.Parse(reader.ReadLine());
  string encryptionKey = (string)jObject["key"];
  string originURL = (string)jObject["origin_url"];
}

至于为什么using块是好的,并且比手动调用Dispose ... image更好...如果using块中的任何代码在你关闭所有内容的行之前引发异常?你基本上泄漏了IDisposable对象在底层管理的任何非托管资源。 using确保正确调用Dispose,即使面对异常(通过注入适当的try / finally块)。

如果可能(即,您不必保留跨范围的某些IDisposable的生命周期),您应该利用using块,除非它们减少了您必须编写的样板代码量为了确保您自己的代码安全无误。

答案 6 :(得分:1)

@ Darin的答案显示了代码。它们是好的原因是使用块会导致编译器吐出代码,这些代码会在退出块之前自动调用对象上的“Dispose”(让它立即释放它可能正在使用的任何资源) - 即使抛出异常也是如此在块内

答案 7 :(得分:1)

using相当于try.. finally,因此即使在块中抛出异常,处理程序也会运行。

答案 8 :(得分:1)

使用-block有两个原因:

  • 他们看起来很好
  • 块内的代码经常会抛出异常。所以你需要尝试 - 终于

最后是一个使用块,例如

using (Somthing somthing=...)
{
    DoActions(somthing);
}

与以下结果相同:

{Somthing somthing=...
    try
    {
        DoActions(somthing);
    }
    finally
    {
        somthing.Dispose();
    }
}//the outer bracket limits the variable