使用 using 返回 IEnumerable
我遇到了一个有趣的问题,这是完全有道理的。我有一个像这样的通用方法:
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
我很难找到解决这个问题的最佳方法,我知道我可以返回一个具体的列表,但如果可能的话,我想避免这种情况,但我还是可以在委托中移动 using 语句。 ,如果我可以避免为每个代表这样做,那就太好了。
Interesting problem I ran across which makes total sense. I have a generic method like so:
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;
}
In one case, the resultDelegate
's return type (TResult
) is IEnumerable<object>
. The problem is that the Run
function returns immediately due to deferred execution, disposing the SqlDataReader. Later in the code when I try to read through the results (which the delegate does reader.Read()
, I get an InvalidOperationException: Invalid attempt to call Read when reader is closed.
I'm having a hard time figuring out the best way around this. I know I can return a concrete list, but I would like to avoid that if possible. I can also move the using statement inside the delegate, but once again, if I can avoid doing that for every delegate it would be nice. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许:
Perhaps: