c# - "using"语句与花括号

标签 c# scope using curly-braces

我想知道为什么我们在 C# 中使用 using 语句。查了一下,发现是用来执行语句,然后清理对象的。所以我的问题是:如果我们打开和关闭大括号 ( { } ) 来定义范围,这不是一回事吗?

使用语句:

using (SqlConnection conn = new SqlConnection(connString)) {
     SqlCommand cmd = conn.CreateCommand();
     cmd.CommandText = "SELECT * FROM Customers";
     conn.Open();
     using (SqlDataReader dr = cmd.ExecuteReader()) {
          while (dr.Read()) 
          // Do Something...
     }
}

花括号:

{
     SqlConnection conn = new SqlConnection(connString);
     SqlCommand cmd = conn.CreateCommand();
     cmd.CommandText = "SELECT * FROM Customers";
     conn.Open();
     {
          SqlDataReader dr = cmd.ExecuteReader();
          while (dr.Read()) 
          // Do Something...
     }
}

这两种方法有什么显着差异吗?

最佳答案

好吧,使用(当且仅当该类实现IDisposable 接口(interface)时才合法)

using (SqlConnection conn = new SqlConnection(connString)) {
  // Some Code
  ...
}

等于这段代码

SqlConnection conn = null;

try {
  SqlConnection conn = new SqlConnection(connString);

  // Some Code
  ...
}
finally {
  if (!Object.ReferenceEquals(null, conn))
    conn.Dispose();
}

C# 不具有与 C++ 相同的行为,因此不要像在 C++ 中那样在 C# 中使用 {...} 模式:

{
  SqlConnection conn = new SqlConnection(connString);
  ...
  // Here at {...} block exit system's behavior is quite different:
  //
  // C++: conn destructor will be called, 
  // resources (db connection) will be safely freed
  //
  // C#:  nothing will have happened! 
  // Sometimes later on (if only!) GC (garbage collector) 
  // will collect conn istance and free resources (db connection). 
  // So, in case of C#, we have a resource leak 
}

关于c# - "using"语句与花括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18227852/

相关文章:

c# - 方法范围的实例变量

scope - Ninject InRequestScope 回退到 InThreadScope

c++ - 减轻头文件中的长限制

c# - 这两个使用 using 关键字的实现之间的差异

c# - .NET 4.0 框架的 EXIF 库

c# - 解决 caSTLe windsor 中的依赖项时如何将一种类型转换为另一种类型

c# - Visual Studio 2012/C# 中断代码执行,未设置断点

javascript - 破解 JS : Thoughts on mixing in some object as arguments (or inner variables) for external functions (like **kwargs) w/o using this

c# - Linq 选择 : Set specific value for first occurrence only

c# - 妥善处理变量。使用语句是否足够?