【发布时间】: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