private Func GenerateWriter()
{
MethodInfo appendMethod = typeof(StringBuilder).GetMethod("Append",
new[] { typeof(string) });
var buffer = Expression.Variable(typeof(StringBuilder), "buffer");
var writer = new List<Expression>();
var source = Expression.Parameter(typeof(string[]));
writer.Add(Expression.Assign(buffer, Expression.New(typeof(StringBuilder))));
//add some strings to buffer
writer.Add(Expression.Call(buffer, "ToString", null));
var f = Expression.Lambda<Func<string[], string>>
(Expression.Block(writer.ToArray()), source).Compile();
return f;
}
I have gotten such message:
variable ‘buffer’ of type ‘System.Text.StringBuilder’
referenced from scope ”, but it is not defined
I do not understand what the error. Everything seems correct.
Help me, please!
I believe the problem is your call to
Expression.Block. You need to specify the variables declared by the block:Give that a try. (I removed the
ToArraycall as there’s an overload which takes anIEnumerable<Expression>.)