【问题标题】:Hello world with Expression Trees带有表达式树的 Hello World
【发布时间】:2012-12-14 17:46:56
【问题描述】:

我正在尝试掌握表达式树。我想我会先编写一个简单的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"); 会更简单一些。

【问题讨论】:

  • 我尝试剪切和粘贴您的代码,但出现更多编译器错误。您可以发布更多代码吗?
  • @IanO'Brien,很可能是我抄错了代码。你得到什么编译器错误?

标签: c# .net lambda linq-expressions


【解决方案1】:

您需要为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])
            });

【讨论】:

    猜你喜欢
    • 2019-03-19
    • 2012-08-07
    • 2020-04-15
    • 2014-05-02
    • 2018-09-24
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多