Вопрос

Good day. I have method for recursive traverse TreeNode in TreeView:

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. 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. If these are the ones from System.Windows.Forms, you'll need to call Cast as well.

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.

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 с атрибуция
Не связан с StackOverflow
scroll top