2012-12-14 118 views
3

我想要与表达树握手。我想我首先编写一个简单的helloWorld函数,创建一个StringBuilder,附加"Helloworld",然后输出字符串。这是我到目前为止有:表情树你好世界

var stringBuilderParam = Expression.Variable 
    typeof(StringBuilder), "sb"); 

var helloWorldBlock = 
    Expression.Block(new Expression[] 
     { 
      Expression.Assign(
       stringBuilderParam, 
       Expression.New(typeof(StringBuilder))), 
      Expression.Call(
       stringBuilderParam, 
       typeof(StringBuilder).GetMethod(
        "Append", 
        new[] { typeof(string) }), 
       new Expression[] 
        { 
         Expression.Constant(
          "Helloworld", typeof(string)) 
        }), 
      Expression.Call(
       stringBuilderParam, 
       "ToString", 
       new Type[0], 
       new Expression[0]) 
     }); 

var helloWorld = Expression.Lamda<Func<string>>(helloWorldBlock).Compile(); 

Console.WriteLine(helloWorld); 
Console.WriteLine(helloWorld()); 
Console.ReadKey(); 

Compile()抛出一个类型的范围“”引用的“System.Text.StringBuilder”的InvalidOperationException

变量“SB”,但它没有定义

很明显,我不会以正确的方式去做这件事。有人能指引我朝着正确的方向吗?我知道Console.WriteLine("HelloWorld");会比较简单一些。

+0

我试图剪切并粘贴您的代码,但出现更多编译器错误。有没有更多的代码可以发布? –

+0

@ IanO'Brien,它可能是我错误地抄录了代码。你得到什么编译器错误? – Jodrell

回答

3

您需要指定BlockExpression的变量才能使用它们。只需致电another overload

var helloWorldBlock = 
    Expression.Block(
     new ParameterExpression[] {stringBuilderParam}, 
     new Expression[] 
      { 
       Expression.Assign(
        stringBuilderParam, 
        Expression.New(typeof (StringBuilder))), 
       Expression.Call(
        stringBuilderParam, 
        typeof (StringBuilder).GetMethod(
         "Append", 
         new[] {typeof (string)}), 
        new Expression[] 
         { 
          Expression.Constant(
           "Helloworld", typeof (string)) 
         }), 
       Expression.Call(
        stringBuilderParam, 
        "ToString", 
        new Type[0], 
        new Expression[0]) 
      }); 
+0

那么简单,谢谢 – Jodrell