【问题标题】:What is the difference between Dispose and Close? [duplicate]处置和关闭有什么区别? [复制]
【发布时间】:2011-03-14 02:39:59
【问题描述】:

可能重复:
Close and Dispose - which to call?

嗨,

看了一些网页,还是不明白C#中Dispose和Close方法的区别。

我们来取样:

using (SqlConnection sqlConnection = new SqlConnection())
{
    // Execute an insert statement (no breaks, exceptions, returns, etc.)
}

还有第二个:

SqlConnection sqlConnection = new SqlConnection();
// Execute an insert statement (no breaks, exceptions, returns, etc.)
sqlConnection.Close();

这两段代码相似吗?两者都只是为了方便而提供(因为在某些情况下using 不是解决方案?或者行为有所不同?

那么为什么有些类提供Close 方法,我什么时候应该在我创建的IDisposable 类中放置Close 方法?

【问题讨论】:

标签: c# dispose idisposable


【解决方案1】:

你的两个代码 sn-ps 是等价的。

实现IDisposable 并公开Close 的.NET 类,这样做是为了增加方便,因为Close 方法的名称稍微友好一些。通常一个人打电话给另一个人。

如果您实现自己的一次性类,则不需要添加Close 方法,除非您喜欢拥有一个。

【讨论】:

  • 这几乎是正确的。 DisposeClose 是相同的除了对于数据库连接类。
猜你喜欢
  • 2012-12-07
  • 1970-01-01
  • 2015-11-23
  • 2013-02-13
  • 2011-04-26
  • 2016-09-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多