C#使用关键字的范围

Rya*_*ies 4 c# using-statement

据我所知,每当我实例化一个实现IDisposable的类时,我都应该使用该using关键字以确保它被正确处理掉.

像这样:

using (SecureString s = new SecureString())
{

}
Run Code Online (Sandbox Code Playgroud)

以上内容对我来说很容易理解 - 我可以s在这些括号内使用但是一旦我离开这些括号,我就再也不能参考了s.范围很容易看到.

但我不明白的是当你使用using没有封闭括号时它是如何工作的.

private void Function()
{
    // Some code here

    using (SecureString s = new SecureString())

    // more code here
}
Run Code Online (Sandbox Code Playgroud)

你根本不需要使用括号...所以...如果using关键字没有括号,我怎么知道我能在哪里使用这个对象以及它在哪里处理?

Tre*_*ott 8

几乎在C#中的每一种情况下,当你可以选择使用大括号时,你可以用一行代码替换它们.

考虑一个if语句:

if (someBool)
    DoSomething();
else
    DoSomethingElse();
Run Code Online (Sandbox Code Playgroud)

这与以下一样有效:

if (someBool)
{
    // do lots of things
}
else
    DoSomethingElse();
Run Code Online (Sandbox Code Playgroud)

这可能几乎普遍适用于任何时候你可以使用{}括号.

关于这个using声明的好处是你可以像这样嵌套它们:

using (var stream = new NetworkStream(...))
using (var sslStream = new SslStream(stream))
using (var reader = new StreamReader(sslStream))
{
    reader.WriteLine(...);
}
Run Code Online (Sandbox Code Playgroud)

这相当于以下内容:

using (var stream = new NetworkStream(...))
{
    using (var sslStream = new SslStream(stream))
    {
        using (var reader = new StreamReader(sslStream))
        {
            reader.WriteLine(...);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

虽然我认为你同意它看起来更好看.


Ror*_*san 6

一个using没有括号意味着using在接下来的语句的范围 -在以同样的方式if条件下工作.

using (SecureString s = new SecureString())
    s.Foo(); // Works
s.Foo(); // out of scope
Run Code Online (Sandbox Code Playgroud)

作为个人偏好,我总是包括大括号,即使是单个语句if/ using构造,也可以避免混淆这样的情况.