.net - 使用 using 返回 IEnumerable

标签 .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。稍后在代码中,当我尝试阅读结果时(委托(delegate)执行 reader.Read() ,我得到 InvalidOperationException: Invalid attempt to call Read when reader is closed.

我很难找到解决这个问题的最佳方法。我知道我可以返回一个具体的列表,但如果可能的话我想避免这种情况。我还可以在委托(delegate)内移动 using 语句,但是,如果我可以避免为每个委托(delegate)执行此操作,那就太好了。有什么想法吗?

最佳答案

也许:

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;

}

关于.net - 使用 using 返回 IEnumerable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4000270/

相关文章:

c# - 本地调试 - 云服务和 Service Fabric 与应用服务

c# - wcf服务的奇怪问题

c# - 图像回调 c++ 到 c#

c# - 如何让一个 View 模型更新另一个 View 模型的属性?

ios - Swift:UIPopoverPresentationControllerDelegate 委托(delegate)变为 nil

c# - 如何确定是否正在处理 .NET 异常?

c# - 在一个组合框中显示数据库中的多列

C# event += delegate {} 在 VB.NET 中等效

整个类的 C# IDisposable 对象

c# - Entity Framework 的“使用”关键字与类字段