C# Hello world与表情树
我正在努力掌握表达式树。我想首先编写一个简单的C# Hello world与表情树,c#,.net,lambda,linq-expressions,C#,.net,Lambda,Linq Expressions,我正在努力掌握表达式树。我想首先编写一个简单的helloWorld函数,创建一个StringBuilder,附加“helloWorld”,然后输出字符串。这就是我到目前为止所做的: var stringBuilderParam = Expression.Variable typeof(StringBuilder), "sb"); var helloWorldBlock = Expression.Block( new Expression[] {
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();
var stringBuilderParam=Expression.Variable
类型(StringBuilder),“sb”);
变量helloWorldBlock=
Expression.Block(新表达式[])
{
表达式.赋值(
stringBuilderParam,
Expression.New(typeof(StringBuilder)),
表情,打电话(
stringBuilderParam,
typeof(StringBuilder).GetMethod(
“追加”,
新[]{typeof(string)}),
新表达式[]
{
表达式.常数(
“Helloworld”,类型(字符串))
}),
表情,打电话(
stringBuilderParam,
“ToString”,
新类型[0],
新表达式[0])
});
var helloWorld=Expression.Lamda(helloWorldBlock.Compile();
Console.WriteLine(helloWorld);
Console.WriteLine(helloWorld());
Console.ReadKey();
Compile()
抛出一个InvalidOperationException
“System.Text.StringBuilder”类型的变量“sb”从作用域“”引用,但未定义该变量
很明显,我做得不对。有人能给我指出正确的方向吗
显然,我意识到自己在做
Console.WriteLine(“HelloWorld”)代码>会稍微简单一些。您需要为块表达式指定变量才能使用它们。只要打电话:
我试图剪切并粘贴您的代码,但编译器错误更多。还有其他代码可以发布吗?@IanO'Brien,很可能是我转录的代码不正确。您遇到了什么编译器错误?
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])
});