突破值得關注的是從有一個foreach打破有道使得IEnumerable的<>知道,我做它應該清理。關於收益率的回報,並從一個foreach
考慮下面的代碼:
private static IEnumerable<Person> getPeople()
{
using (SqlConnection sqlConnection = new SqlConnection("..."))
{
try
{
sqlConnection.Open();
using (SqlCommand sqlCommand = new SqlCommand("select id, firstName, lastName from people", sqlConnection))
{
using (SqlDataReader reader = sqlCommand.ExecuteReader())
{
while (reader.Read())
yield return new Person(reader.GetGuid(0), reader.GetString(1), reader.GetString(2));
}
}
}
finally
{
Console.WriteLine("finally disposing of the connection");
if (sqlConnection.State == System.Data.ConnectionState.Open)
sqlConnection.Close();
}
}
}
如果他的消費不會在foreach突破則寄託都是好的,讀者將返回false,while循環willend和函數清理數據庫命令和連接。但是如果在我完成之前調用者從這個foreach中斷了,會發生什麼?
也看到http://stackoverflow.com/questions/1400146/are-there-any-pitfalls-to-using-an-ienumerablet-return-type-for-sql-data/1400195# 1400195 – 2009-09-10 16:36:47