继承于这个问题,我发现自己一遍又一遍地写以下代码:
SqlCommand command = new SqlCommand();
// Code to initialize command with what we want to do
using (SqlConnection connection = openConnection())
{
command.Connection = connection;
using (SqlDataReader dataReader = thisCommand.ExecuteReader())
{
while (dataReader.Read())
{
// Do stuff with results
}
}
}
嵌套两个using语句有些繁琐。有没有一种方法可以“告诉”SqlDataReader它拥有命令,并告诉命令它拥有连接?
如果有这样的方法,那么我可以编写一个帮助方法,可以这样调用:
// buildAndExecuteCommand opens the connection, initializes the command
// with the connection and returns the SqlDataReader object. Dispose of the
// SqlDataReader to dispose of all resources that were acquired
using(SqlDataReader reader = buildAndExecuteCommand(...))
{
// Do stuff with reader
}
还是我必须硬着头皮自己编写SqlDataReader的包装器?(注:SqlDataReader是一个用于从数据库中读取数据的类)