是否有理由在上次使用时检查 null ?在我看来,它很可能不需要?
using (var connection = new SqlConnection(connectionString))
{
using (var command = new SqlCommand(commandString, connection))
{
using (var reader = command.ExecuteReader())
{
if (reader != null) {
// Use the reader
}
}
}
}
EDIT:
如果我像这样使用它,我应该在使用中关闭 reader.Close() 和 connection.Close() 吗:
using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetailsDZP))
using (var sqlWrite = new SqlCommand(preparedCommand, varConnection)) {
while (sqlWrite.Read()) {
//something to do.
}
sqlWrite.Close();
varConnection.Close();
}
public static SqlConnection sqlConnectOneTime(string varSqlConnectionDetails) {
SqlConnection sqlConnection = new SqlConnection(varSqlConnectionDetails);
sqlConnect(sqlConnection);
if (sqlConnection.State == ConnectionState.Open) {
return sqlConnection;
}
return null;
}
在下面的示例中是否需要使用 close 或者我可以跳过这两个?
sqlWrite.Close();
varConnection.Close();
带着敬意,
MadBoy
不,这没有必要。
但这是从的定义ExecuteReader http://msdn.microsoft.com/en-us/library/9kcbe65k.aspx,它与 using 子句无关。ExecuteReader
要么返回一个(非空)DataReader 对象,要么抛出异常。
中的表达式为if
语句将始终为真(如果达到)。
并通过省略if
和所有多余的大括号对可以使这更容易阅读:
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(commandString, connection))
using (var reader = command.ExecuteReader())
{
// Use the reader
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)