【问题标题】:Recursive call - Action lambda递归调用 - 动作 lambda
【发布时间】:2011-04-30 18:52:01
【问题描述】:

我在这里做错了什么?如何执行我的操作?

var recurse = new Action<IItem, Int32>((item, depth) =>
{
    if (item.Items.Count() > 0) recurse(item, depth + 1); // red squiggly here

    // ...
});

当我打电话给recurse“方法、委托或事件预期”时,我得到一个红色波浪线


更新

我已接受 Homam 的回答。我只是想为相同的添加/共享另一种语法...但是我发现这更容易...

Action<IEnumerable<Item>> Recurse = null;

Recurse = item =>
{
    if (item.Items != null) Recurse(item.Items);

    // ...
};

【问题讨论】:

    标签: c# recursion delegates


    【解决方案1】:

    只需定义委托Action 并在递归调用之前为其分配null。

    Action<IItem, Int32> recurse = null;
    

    然后

    recurse = new Action<IItem, Int32>((item, depth ) =>
    {
        if (item.Items.Count() > 0) recurse(item, depth + 1); // red squiggly here
        // ...
    });
    

    祝你好运!

    【讨论】:

    • 我不想不得不拆分定义和实现。有什么办法可以在一行代码中做到这一点?
    • 没有。 Eric 在他的博客文章中解释了原因(通常会出现):blogs.msdn.com/b/ericlippert/archive/2006/08/18/706398.aspx
    • @Ron:好消息。有点奇怪的感觉:)
    • 有一些方法可以做匿名递归,比如定义一个 Y-Combinator,但是这个要简单得多。见blogs.msdn.com/b/wesdyer/archive/2007/02/02/…
    • Eric 博客上的 cmets 有一个定点组合器,允许您在声明点实现 lambda,无需拆分。
    猜你喜欢
    • 2018-12-05
    • 2022-11-30
    • 2016-07-06
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    • 2019-06-20
    • 1970-01-01
    相关资源
    最近更新 更多