3

我正在尝试运行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
4

1 回答 1

5
  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);
     };
    }

那是因为Tree<T> t是一个声明并且(t,a) => 是另一个声明..实际上与说的相同:

int someFunction(T t, U a)
//Assuming int is the return type

无论如何要修复:更改t为另一个标识符..n例如

df = (n,a) =>{
           if (n == null) return;
           a(n.Value);
           df(n.Left, a);
           df(n.Right, a);
         };
        } 
于 2013-02-18T11:28:29.333 回答