3

我正在尝试掌握表达式树。我想我会先编写一个简单的helloWorld函数来创建 a StringBuilder, appends "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");会更简单一些。

4

1 回答 1

3

您需要指定变量BlockExpression才能使用它们。只需调用另一个重载

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])
            });
于 2012-12-14T18:06:27.047 回答