0

私はこの2つの方法を持っています

public static void NavigateAndExecute(Node root, Action<Node> actionToExecute)
{
    if (root == null || root.Children == null || root.Children.Count == 0)
        return;
    actionToExecute(root);
    foreach (var node in root.Children)
    {
        actionToExecute(node);
        NavigateAndExecute(node, actionToExecute);
    }
}
public static void NavigateAndExecute(List<Node> root, Action<Node> actionToExecute)
{
    if (root == null || root.Count == 0)
        return;
    foreach (var node in root)
    {                
        NavigateAndExecute(node, actionToExecute);
    }
}

ノードクラスは

public class Node
{
    public String Name { get; set; }
    public List<Node> Children { get; set; }
}

この2つのメソッドは、Nodeクラスだけで機能し、任意のタイプTの任意のヘルプで機能させることができます。

4

4 に答える 4

2

子セレクターIEnumerable<T>を使用する静的拡張メソッドを作成できます。 Func<T, IEnumerable<T>>

    public static void TraverseAndExecute<T>(this IEnumerable<T> items, Func<T, IEnumerable<T>> selector, Action<T> actionToExecute)
    {
        if (items != null)
        {
            foreach (T item in items)
            {
                actionToExecute(item);
                TraverseAndExecute(selector(item), selector, actionToExecute);
            }
        }
    }

Nodeクラスでの使用法:

List<Node> nodes = // ...
nodes.TraverseAndExecute(n => n.Children, n => /* action here */);
于 2012-05-03T11:23:44.860 に答える
1

私が以前に実装したものが欲しいと思います。Name2main メソッドでの new プロパティの使用に注意してください。

public static class Tree<N>
    where N : Tree<N>.Node
{
    public class Node
    {
        public String Name { get; set; }
        public List<N> Children { get; set; } 
    }

    public static void NavigateAndExecute(N root, Action<N> actionToExecute)
    {
        if (root == null)
            return;
        actionToExecute(root);

        if (root.Children == null || root.Children.Count == 0)
            return;
        NavigateAndExecute(root.Children, actionToExecute);
    }

    public static void NavigateAndExecute(List<N> root, Action<N> actionToExecute)
    {
        if (root == null || root.Count == 0)
            return;
        foreach (var node in root)
        {
            NavigateAndExecute(node, actionToExecute);
        }
    } 

}

public class Node2 : Tree<Node2>.Node
{
    public string Name2 { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var root = new Node2();
        Tree<Node2>.NavigateAndExecute(root, n => {
            Console.WriteLine(n.Name2);
        });
    }
}
于 2012-05-03T11:36:45.347 に答える
1

クラスnode.Children固有のプロパティと思われるものにアクセスしているようです。Nodeしたがって、メソッドをジェネリック メソッドに変換するだけでは、コードは機能しません。

ただし、次のような一般的な制約を使用してこれを実現できます。

public static void NavigateAndExecute<T>(List<T> root, Action<T> actionToExecute) where T: Node
于 2012-05-03T11:21:39.070 に答える
1

Generic Tree Collection が必要です。私は1年前に書いたものをオープンソース化しました:

http://simplygenius.net/Article/TreeCollection2

Tree データ構造を使用することに反対する意見は知っていますが、場合によってはそれらが必要な場合もあります。

于 2012-05-03T11:43:50.090 に答える