c#using语句不带分号

时间:2016-07-06 20:11:48

标签: c# ado.net using

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

matlab.graphics.eventdata.LegendEntry

任何人都可以解释为什么使用(SqlCommand ..)不以分号结尾。我的第二个问题一般是在使用之后我们必须要{}表示使用变量的范围为什么在这种情况下它会丢失?以及如何处置命令对象?

3 个答案:

答案 0 :(得分:4)

  

任何人都可以解释为什么使用(SqlCommand ..)不以分号结尾

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

这与'如果'例如。

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)");
  

我的第二个问题一般是在使用之后我们必须要{}   指出使用变量的范围为什么在这种情况下它会丢失?

不是,仔细观察。

  

以及如何处置命令对象?

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

答案 1 :(得分:0)

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

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

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

答案 2 :(得分:0)

  
      
  1. 任何人都可以解释为什么使用(SqlCommand ..)不以分号结尾。
  2.   

像使用,If,For和Foreach这样的关键词不需要;标志着结局 因为它还没有结束!你永远不会觉得这样的代码很有用。

If(true);//This is totally meaningless code
Console.WrtieLine("Hello world!");
  
      
  1. 我的第二个问题一般是在使用之后我们必须要{}表示使用变量的范围为什么在这种情况下它会丢失?
  2.   

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

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. 以及如何处理命令对象?
  2.   

使用Statement的整个概念得到了很好的解释here