代码之家  ›  专栏  ›  技术社区  ›  Nelson Rothermel

使用返回IEnumerable

  •  2
  • Nelson Rothermel  · 技术社区  · 15 年前

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

    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 回复  |  直到 15 年前
        1
  •  5
  •   Jeff    15 年前

    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;
    
    }