我想要与表达树握手。我想我首先编写一个简单的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");
会比较简单一些。
我试图剪切并粘贴您的代码,但出现更多编译器错误。有没有更多的代码可以发布? –
@ IanO'Brien,它可能是我错误地抄录了代码。你得到什么编译器错误? – Jodrell