c# using 不带分号的语句

c# using statements without semicolon

我在网上找到了以下代码:

using (SqlConnection con = new SqlConnection(connectionString))
    {
        //
        // Open the SqlConnection.
        //
        con.Open();
        //
        // The following code uses an SqlCommand based on the SqlConnection.
        //
        using (SqlCommand command = new SqlCommand("SELECT TOP 2 * FROM Dogs1", con))
        using (SqlDataReader reader = command.ExecuteReader())
        {
        while (reader.Read())
        {
            Console.WriteLine("{0} {1} {2}",
            reader.GetInt32(0), reader.GetString(1), reader.GetString(2));
        }
        }
    }

任何人都可以向我解释为什么使用 (SqlCommand ..) 不以分号结尾。我的第二个问题通常是在使用之后我们必须有 {} 来指示使用变量的范围为什么在这种情况下它丢失了?以及如何,何时处理命令对象?

using 结构不要求语句以分号结尾。

using 结构会自动确保正确处理您的对象。

如果 {} 不存在,则范围是下一个语句。在您的情况下,这是整个 using(SqlReader...) 块,因为它的范围是 {}

can anyone explain me why using (SqlCommand ..) doesn't end with semicolon

因为 using 命令将 运行 恰好是一个块:下一个块。该块只能是一个语句。如果你在末尾放一个分号,它什么都不做(运行 一个空语句)。

这与 'if' 的情况相同。

if(a==b)
   Console.Write("they are equal!");

Console.Write("I'm outside the if now because if only runes one block");

但是

if(1==2);
Console.Write("I will always run because the if ends with a semicolon! (executes an empty statement)");

my second question is generally after using we have to have { } to indicate scope of that using variable why in this case it is missing?

不是,仔细看

and how, when will it dispose command object?

它会在块结束时调用 object.Dispose()(如果它不为空)(即使它抛出异常)。

  1. can anyone explain me why using (SqlCommand ..) doesn't end with semicolon.

Using、If、For 和 Foreach 等关键字不需要 ;标记结束 因为还没有结束!您永远不会发现这样有用的代码。

If(true);//This is totally meaningless code
Console.WrtieLine("Hello world!");
  1. my second question is generally after using we have to have { } to indicate scope of that using variable why in this case it is missing?

因为在这种情况下可以安全地确定外部 using 块的范围。

using (SqlCommand command = new SqlCommand("SELECT TOP 2 * FROM Dogs1", con))
using (SqlDataReader reader = command.ExecuteReader())

同样你也可以这样写

for (int i = 0; i < 3; i++)
    for (int j = 0; j < 2; j++)
    {
        Console.WriteLine(string.Format("i = {0}, j ={1}",i, j));
    }
//i and j are no longer accessible from this line after
//because their scopes ends with the }
  1. and how, when will it dispose command object?

很好地解释了使用语句的整个概念here