从 this 开始问题,我发现自己一遍又一遍地编写以下代码:
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 上编写自己的包装器?
最佳答案
一件事是编写一个为您处理的方法,将每个结果回调到一个委托(delegate)中。例如:
using (SqlConnection connection = openConnection())
{
command.Connection = connection;
ExecuteReaderWithCommand(command, reader =>
{
// Do stuff with the result here.
});
}
然后 ExecuteReaderWithCommand 会是这样的:
public static void ExecuteReaderWithCommand(SqlCommand command,
Action<SqlDataReader> action)
{
using (SqlDataReader dataReader = thisCommand.ExecuteReader())
{
while (reader.Read())
{
action(reader);
}
}
}
如果您愿意,可以将其作为 SqlCommand
的扩展方法。哎呀,如果你愿意的话,你也可以去城里让它为你打开连接……你越能抽象出“打开/使用/关闭”的想法,就越好。
关于c# - 将 SqlDataReader 用作资源的习惯用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1063095/