Problem with expressions variable 'buffer' of type 'System.Text.StringBuilder' referenced from scope '', but it is not defined
private Func GenerateWriter()
{
MethodInfo appendMethod = typeof(StringBuilder).GetMethod("App开发者_开发百科end",
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:
Expression.Block(new[] { buffer }, writer)
Give that a try. (I removed the ToArray
call as there's an overload which takes an IEnumerable<Expression>
.)
精彩评论