表达树的Hello世界

时间:2012-12-14 17:46:57

标签: c# .net lambda linq-expressions

我正试图掌握表情树。我想我首先编写一个简单的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()会引发InvalidOperationException

  从范围''引用的'System.Text.StringBuilder'类型的变量'sb',但它未定义

显然,我没有以正确的方式解决这个问题。有人能指出我正确的方向吗?


显然,我意识到做Console.WriteLine("HelloWorld");会更简单。

1 个答案:

答案 0 :(得分: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])
            });