Код: Выделить всё
static class Functions
{
static public Expression GetOne()
{
//Returns something like this () => {int x; return x +1;}
var variable = Expression.Variable(typeof(int));
var f = Expression.Lambda(
Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Add(variable, Expression.Constant(1)))
));
return f;
}
static public Expression ApplyTenTimes()
{
var i = Expression.Variable(typeof(int));
var breakLabel = Expression.Label();
var f = GetOne();
var loop = Expression.Lambda(
Expression.Block(
new[] { i },
Expression.Block(
new Expression[] {
Expression.Loop(Expression.Block(
Expression.IfThen(Expression.Equal(i, Expression.Constant(10)), Expression.Break(breakLabel)),
Expression.PostIncrementAssign(i),
Expression.Call(typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }), Expression.Call( Expression.Invoke(f),typeof(int).GetMethod("ToString", new Type[0]))
))),
Expression.Label(breakLabel),
Expression.Invoke(f)
})));
return loop;
}
}
Код: Выделить всё
f = Functions.GetOne().Compile();
IEnumerable a = Enumerable.Range(0, 9).Select(_ => f()).ToList();
//Prints 1
Console.WriteLine(f());
f = Functions.ApplyTenTimes().Compile();
//Prints 1, ..., 10, 1
Console.WriteLine(f());
Подробнее здесь: https://stackoverflow.com/questions/787 ... le-leaking