【发布时间】:2009-06-30 11:07:32
【问题描述】:
继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 上编写自己的包装器?
【问题讨论】:
-
其实,上面的SqlCommand也应该在using语句中,所以你会有3个嵌套语句。
标签: c# .net sql sql-server