使用返回IEnumerable

时间:2010-10-22 19:28:05

标签: .net delegates using-statement deferred-execution

有趣的问题我遇到了很有意义。我有一个像这样的通用方法:

public TResult Run<TResult>(Func<SqlDataReader, TResult> resultDelegate)
{
   TResult result;

   using (SqlDataReader reader = command.ExecuteReader()) // command is SqlCommand with attached SqlConnection
   {
      result = resultsDelegate(reader);
   }

   // Some other unrelated code (but that's why result has a variable)

   return result;
}

在一种情况下,resultDelegate的返回类型(TResult)为IEnumerable<object>。问题是Run函数由于延迟执行而立即返回,处理SqlDataReader。稍后在代码中,当我尝试阅读结果时(代理人reader.Read(),我得到InvalidOperationException: Invalid attempt to call Read when reader is closed.

我很难找到解决这个问题的最佳方法。我知道我可以返回一个具体的清单,但如果可能的话我想避免这样做。我也可以在委托中移动using语句,但是再一次,如果我可以避免为每个委托做这个,那就太好了。有什么想法吗?

1 个答案:

答案 0 :(得分:5)

也许:

public TResult Run<TResult>(Func<SqlDataReader, TResult> resultDelegate)
{
   TResult result;

   using (SqlDataReader reader = command.ExecuteReader()) // command is SqlCommand with attached SqlConnection
   {
      result = resultsDelegate(reader);
      if (typeof(TResult) == typeof(IEnumerable<object>)) 
      {
         var enumerable = result as IEnumerable<object>;
         if (enumerable != null) 
         {
            result = enumerable.ToList();  
         }
      }
   }

   // Some other unrelated code (but that's why result has a variable)

   return result;

}