【问题标题】:Recursion and anonymous method in C#C#中的递归和匿名方法
【发布时间】:2014-03-07 10:39:27
【问题描述】:
美好的一天。我在 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);
}
}
但我必须有多余的方法“ShowNode”,它不会在其他任何地方使用。如何使这个方法匿名,并将这两种方法合并?
【问题讨论】:
标签:
c#
recursion
treeview
anonymous-methods
【解决方案1】:
如果您打算将其拆分出来,我实际上会将递归部分与“您对每个节点的操作”部分分开。所以是这样的:
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);
}
}
那么你可以这样称呼它:
allNodes.ApplyRecursively(node => MessageBox.Show(node.ToString()),
node => node.Nodes);
这是假设您使用正确的通用 TreeView / TreeNode 类对。如果这些是来自System.Windows.Forms 的,您还需要致电Cast。
allNodes.Cast<TreeNode>()
.ApplyRecursively(node => MessageBox.Show(node.ToString()),
node => node.Nodes.Cast<TreeNode>());
【解决方案2】:
我会保留一个单独的方法。它通常比使用类型为 Action<TreeNode>(或其他)的变量、为其分配 Action/lambda/delegate,然后通过变量调用 Action 更简洁。
但是..
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);
}
}