开发者

Problem with expressions variable 'buffer' of type 'System.Text.StringBuilder' referenced from scope '', but it is not defined

开发者 https://www.devze.com 2023-01-07 22:22 出处:网络
private Func GenerateWriter() { MethodInfo appendMethod = typeof(StringBuilder).GetMethod(\"App开发者_开发百科end\",

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>.)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号