Why is this error “local variable cannot be declared in this scope because it … is already used”?
我正试图运行EricLippert的博客文章中的代码"为什么递归lambda会导致确定的赋值错误?"
但我没有运行(或给出编译"明确的分配错误"),而是得到:
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
为什么?它已经在父级或当前作用域中的何处使用?试图重命名它得到同样的错误如何更改代码来启动此代码?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | 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 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | static void PrintTree<T>(Tree<T> t) { //Traversal<T> df = (t, a)=> ************** Traversal<T> df = null; //======================================== df = (t, a) => { if (t == null) return; a(t.Value); df(t.Left, a); df(t.Right, a); }; } |
那是因为
1 2 | int someFunction(T t, U a) //Assuming int is the return type |
无论如何要修复:将
1 2 3 4 5 6 7 | df = (n,a) =>{ if (n == null) return; a(n.Value); df(n.Left, a); df(n.Right, a); }; } |