简体   繁体   English

C#中的递归和匿名方法

[英]Recursion and anonymous method in C#

Good day. 美好的一天。 I have method for recursive traverse TreeNode in TreeView: 我在TreeView中有递归遍历TreeNode的方法:

public void ShowTree(TreeView tree)
{
    foreach (TreeNode node in tree.Nodes)
    {
        ShowNode(node);
    }
}

private void ShowNode(TreeNode node)
{
    MessageBox.Show(node.ToString());
    foreach (TreeNode child in node.Nodes)
    {
        ShowNode(child);
    }
}

But I must have excess method "ShowNode", that is not used anywhere else. 但我必须有多余的方法“ShowNode”,这在其他任何地方都没有使用。 How to make this method of anonymous and to merge these two methods? 如何制作这种匿名方法并合并这两种方法?

If you are going to split this out, I would actually split the recursion part from the "what you do with each node" part. 如果要拆了这一点,我真的分裂递归部分从“你与每个节点做什么”的一部分。 So something like this: 所以像这样:

public static void ApplyRecursively<T>(this IEnumerable<T> source,
                                       Action<T> action,
                                       Func<T, IEnumerable<T>> childSelector)
{
    // TODO: Validation
    foreach (var item in source)
    {
        action(item);
        childSelector(item).ApplyRecursively(action, childSelector);
    }        
}

Then you can call it as: 然后你可以把它称为:

allNodes.ApplyRecursively(node => MessageBox.Show(node.ToString()),
                          node => node.Nodes);

This is assuming you're using a proper generic TreeView / TreeNode class pair. 这假设您正在使用适当的通用TreeView / TreeNode类对。 If these are the ones from System.Windows.Forms , you'll need to call Cast as well. 如果这些是来自System.Windows.Forms的那些,您还需要调用Cast

allNodes.Cast<TreeNode>()
        .ApplyRecursively(node => MessageBox.Show(node.ToString()),
                          node => node.Nodes.Cast<TreeNode>());

I would keep a separate method. 我会保留一个单独的方法。 It's generally tidier than using a variable typed Action<TreeNode> (or whatever), assigning an Action/lambda/delegate to it, and then invoking the Action through the variable. 通常比使用变量类型的Action<TreeNode> (或其他),为其分配Action / lambda /委托,然后通过变量调用Action更整洁。

But .. 但..

public void ShowTree(TreeView tree)
{
    // Must assign null first ..
    Action<TreeNode> showNode = null;

    showNode = (node) => {
      MessageBox.Show(node.ToString());
      foreach (TreeNode child in node.Nodes)
      {
          // .. so this won't be an "unassigned local variable" error
          showNode(child);
      }
    };

    foreach (TreeNode node in tree.Nodes)
    {
        showNode(node);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM