奇怪的委托参考行为
我需要通过其他处理函数列表(每个函数接受并返回一个 IEnumerable
)传递源函数(返回一个 IEnumerable)的结果。
到目前为止一切都很好,但我还需要允许处理函数对其输入枚举执行多个循环。
因此,我不想传入 IEnumerable
,而是将输入参数更改为 Func
并允许每个函数重新启动如果需要的话可以枚举。
不幸的是,我现在遇到堆栈溢出,其中最终处理函数正在调用自身,而不是将请求传递回链中。
示例代码有点做作,但希望能让您了解我想要实现的目标。
class Program
{
public static void Main(string[] args)
{
Func<IEnumerable<String>> getResults = () => GetInputValues("A", 5);
List<String> valuesToAppend = new List<String>();
valuesToAppend.Add("B");
valuesToAppend.Add("C");
foreach (var item in valuesToAppend)
{
getResults = () => ProcessValues(() => getResults(),item);
}
foreach (var item in getResults())
{
Console.WriteLine(item);
}
}
public static IEnumerable<String> GetInputValues(String value, Int32 numValues)
{
for (int i = 0; i < numValues; i++)
{
yield return value;
}
}
public static IEnumerable<String> ProcessValues(Func<IEnumerable<String>> getInputValues, String appendValue)
{
foreach (var item in getInputValues())
{
yield return item + " " + appendValue;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
getResults
被捕获为变量,而不是值。我不太喜欢您在这里使用的整体方法(看起来很复杂),但是您应该能够通过更改捕获来修复 stackoverflow:附注:
IEnumerable[]< /code> 已经有点可重复,您只需再次调用
) 不是 - 但我认为值得尝试这样做而不需要重复枚举,因为在一般情况下 根本不能保证它能正常工作。foreach
- 就是IEnumerator[]
(尽管 < code>Reset()这是一个更简单的(IMO)实现,具有相同的结果:
getResults
is captured as a variable, not a value. I don't really like the overall approach you're using here (it seems convoluted), but you should be able to fix the stackoverflow by changing the capture:On a side note:
IEnumerable[<T>]
is already kinda repeatable, you simply callforeach
another time - is isIEnumerator[<T>]
that (despite theReset()
) isn't - but also, I think it is worth doing trying to do this without needing to ever repeat the enumeration, since in the general case that simply cannot be guaranteed to work.Here's a simpler (IMO) implementation with the same result: