说我有这两个对象:
OracleConnection connection = new OracleConnection(connectionString); OracleCommand command = new OracleCommand(sql, connection);
要关闭连接或Oracle,我是否必须调用command.Dispose(),connection.Dispose()或两者?
这够好了:
using(connection) { OracleDataReader reader = cmd.ExecuteReader(); // whatever... }
John Saunder.. 17
using (OracleConnection connection = new OracleConnection(connectionString)) { using (OracleCommand command = new OracleCommand(sql, connection)) { using (OracleDataReader reader = cmd.ExecuteReader()) { } } }
如果它实现了IDisposable,并且如果你创建它,那么将它放在using块中.
using (OracleConnection connection = new OracleConnection(connectionString)) { using (OracleCommand command = new OracleCommand(sql, connection)) { using (OracleDataReader reader = cmd.ExecuteReader()) { } } }
如果它实现了IDisposable,并且如果你创建它,那么将它放在using块中.
这两个答案都非常符合目标.您总是希望在任何IDisposeable对象上调用.Dispose().通过包装在"使用"中,您可以使编译器始终为您提供try/finialy块.
1注意,如果你想避免嵌套,可以像这样编写相同的代码:
using (OracleConnection connection = new OracleConnection(connectionString)) using (OracleCommand command = new OracleCommand(sql, connection)) using (OracleDataReader reader = cmd.ExecuteReader()) { // do something here }