时间:2019-05-17 标签:c#using不带分号的语句

ban*_*nsi -1 c# ado.net using

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

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));
        }
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

Gas*_*a79 6

谁能解释一下为什么使用 (SqlCommand ..) 不以分号结尾

因为 using 命令将只运行一个块:后面的块。该块只能是一个语句。如果您在末尾添加分号,它将不会执行任何操作(运行空语句)。

例如,这与“if”的情况相同。

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

Console.Write("I'm outside the if now because if only runes one block");
Run Code Online (Sandbox Code Playgroud)

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

我的第二个问题通常是在使用之后我们必须有 { } 来指示使用变量的范围为什么在这种情况下它丢失了?

不是的,仔细看看。

以及如何、何时处理命令对象?

当块结束时(即使它抛出异常),它将调用 object.Dispose() (如果它不为 null)。