Your situation is very similar to what I sometimes saw when querying the database. In an attempt to separate the logic, you sometimes see the code as follows:
var reader = ExecuteSQL("SELECT ...");
while (reader.Read())
{
}
public SqlDataReader ExecuteSQL(string sql)
{
using (SqlConnection conn = new SqlConnection("..."))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
return cmd.ExecuteReader();
}
}
}
But, of course, this cannot work, because by the time the SqlDataReadermethod returns, the ExecuteSQLconnection has already been closed (deleted).
, , :
ExecuteSQL(reader => {
});
public void ExecuteSQL(string sql, Action<SqlDataReader> processRow)
{
using (SqlConnection conn = new SqlConnection("..."))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
processRow(reader);
}
}
}
}
}
, , - ? - :
MakeAndProcess(c => {
});
public void MakeAndProcess(Action<C> processC)
{
using (var a = new A())
using (var b = new B(a))
{
processC(new C(b));
}
}