我正在尝试运行Eric Lippert 的博客文章中的代码“为什么递归 lambda 会导致明确的分配错误?”
但不是运行(或给出编译“明确的分配错误”我得到:
不能在此范围内声明名为“t”的局部变量,因为它会给“t”赋予不同的含义,后者已在“父或当前”范围中用于表示其他内容
为什么?
它已在父范围或当前范围中使用在哪里?
尝试重命名它得到相同的错误
我应该如何更改代码以启动此代码?
using System;
namespace LippertRecursiveLambdaError
{
class Program
{
static void Main(string[] args)
{
Tree<int> tree = new Tree<int>
(3, new Tree<int>
(4, new Tree<int>(1), null),
new Tree<int>(5));
PrintTree(tree);
Console.ReadLine();
}
delegate void Action<A>(A a);
delegate void Traversal<T>(Tree<T> t, Action<T> a);
static void DepthFirstTraversal<T>(Tree<T> t, Action<T> a)
{
if (t == null) return;
a(t.Value);
DepthFirstTraversal(t.Left, a);
DepthFirstTraversal(t.Right, a);
}
static void Traverse<T>(Tree<T> t, Traversal<T> f, Action<T> a)
{
f(t, a);
}
static void Print<T>(T t)
{
System.Console.WriteLine(t.ToString());
}
/*static void PrintTree<T>(Tree<T> t)
{
Traverse(t, DepthFirstTraversal, Print);
}*/
static void PrintTree<T>(Tree<T> t)
{
//Traversal<T> df = (t, a)=> **************
Traversal<T> df = null;
//========================================
//The next line gives compilation error
//A local variable named 't' cannot be declared in this scope
//because it would give a different meaning to 't',
//which is already used in a 'parent or current' scope to denote something else
df = (t,
a) =>
{
if (t == null) return;
a(t.Value);
df(t.Left, a);
df(t.Right, a);
};
Traverse(t, df, Print);
}//PrintTree
}//class
class Tree<T>
{
public Tree<T> Left;
public Tree<T> Right;
public T Value;
public Tree(T value)
{
Value = value;
}
public Tree(T value, Tree<T> left, Tree<T> right)
{
Value = value;
Left = left;
Right = right;
}
}
}//namespace