c#使用不带分号的语句

c#使用不带分号的语句,c#,ado.net,using,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 (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..)不以分号结尾吗。我的第二个问题通常是在使用之后,我们必须有{}来指示使用变量的范围,为什么在这种情况下它会丢失?它将如何,何时处理命令对象

使用构造不要求语句以分号结尾

使用构造会自动确保对象得到正确处置

如果{}不存在,则作用域是下一个语句。在您的例子中,这就是使用(SqlReader…)的整个过程,因为它的作用域是{}

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

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

例如,“如果”的情况也是如此

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

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

我的第二个问题是,在使用之后,我们必须{} 指出使用变量的范围,为什么在这种情况下缺少该变量

不是,仔细看看

它将如何,何时处理命令对象

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

  • 有人能解释一下为什么使用(SqlCommand..)不以分号结尾吗 像Using、If、For和Foreach这样的关键字不需要一个;结束 因为它还没有结束!您永远不会发现这样的代码有用

    If(true);//This is totally meaningless code
    Console.WrtieLine("Hello world!");
    
  • 我的第二个问题通常是在使用之后,我们必须有{}来指示使用变量的范围,为什么在这种情况下它会丢失
  • 因为在这种情况下,可以安全地确定外部使用块的范围

    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 }
    
    for(int i=0;i<3;i++)
    对于(int j=0;j<2;j++)
    {
    WriteLine(string.Format(“i={0},j={1}”,i,j));
    }
    //之后,i和j不再可从此线路访问
    //因为它们的作用域以}结尾
    
  • 它将如何,何时处理命令对象

  • 使用语句的整个概念都得到了很好的解释。

    该“提供了一种方便的语法,确保正确使用IDisposable对象”,不同于按正确顺序处理对象的方式。@ScottChamberlain不知道这一点。谢谢
    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 }