2012-12-14 116 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