从表达式增加值

时间:2014-07-14 18:10:27

标签: c# .net reflection code-generation linq-expressions

我想写一个闭包并增加它的值,但我无法做到。这是我的代码

        int i = 0;
        Expression<Func<bool>> closurExpression = () =>
                                                  {
                                                      i++;
                                                      return i != 0;
                                                  };

但我得到关于A lambda expression with a statement body cannot be converted to an expression treeAn expression tree may not contain an assignment operator等的多重错误。是否可以不使用Mono.Cecil等外部工具?


问题:我为什么要求它。我想写一个简单的包装器(用于签名Func<T,T> at least,它将计算调用次数。例如:

Wrapper<int> wrapper = () => 5;
for(int i = 0; i < 10; i++)
   wrapper();
int calls = wrapper.Calls; // 10;

我的第一个认识是:

class FunctionWithCounter<T, TResult>
{
    private readonly Func<T, TResult> function;
    public int Calls { get; set; }

    private FunctionWithCounter(Func<T, TResult> function)
    {
        Calls = 0;
        this.function = function;
    }
    public static implicit operator FunctionWithCounter<T, TResult>(Func<T, TResult> func)
    {
        return new FunctionWithCounter<T, TResult>(func);
    }

    public TResult this[T arg]
    {
        get
        {
            Calls++;
            return function(arg);
        }
    }
}

但在我得到那些重复功能后将无法正常工作。例如,此代码

int fact(int n) { return n < 2 ? 1 : n * fact(n - 1); }

对于任何n,呼叫计数将为1。所以想法是:获取源函数,并为方法的每次调用注入Calls的增量。方法somefunc的所有内部调用都应该由我们的方法funcWithInjection替换,在这种情况下,我们也将捕获递归函数。这是我的代码,但它不起作用(注入除外,所以这段代码实际上增加了一个字段值,但我不能将源的方法体添加到尾部并编译它,如果你愿意,可以使用它):

public class FunctionWithCounter<T, TResult> where T : new()
{
    private readonly Func<T, TResult> _functionWithInjection;
    private int _calls;
    public int Calls
    {
        get
        {
            return _calls;
        }
    }

    public FunctionWithCounter(Func<T, TResult> function)
    {
        _calls = 0;
        var targetObject = function.Target ?? new object();
        var dynMethod = new DynamicMethod(new Guid().ToString(), typeof(TResult), new[] { targetObject.GetType(), typeof(T), typeof(FunctionWithCounter<T, TResult>) }, true);

        var ilGenerator = GenerateInjection(dynMethod);
        ilGenerator.Emit(OpCodes.Ret);

        var resDelegate = dynMethod.CreateDelegate(typeof(Func<T, FunctionWithCounter<T, TResult>, TResult>), targetObject);
        var functionWithInjection = (Func<T, FunctionWithCounter<T, TResult>, TResult>)resDelegate;
        var targetMethodBody = function.Method.GetMethodBody();
        Debug.Assert(targetMethodBody != null, "mbody != null");

        //here i need to write method body in the tail of dynamic method.

        _functionWithInjection = function;
        _functionWithInjection = t =>
        {
            functionWithInjection(t, this);
            return default(TResult);
        };
        //finally here should be _functionWithInjection = t => functionWithInjection(t, this);
    }

    private ILGenerator GenerateInjection(DynamicMethod method)
    {
        var callsFieldInfo = GetType().GetField("_calls", BindingFlags.NonPublic | BindingFlags.Instance);
        Debug.Assert(callsFieldInfo != null, "callsFieldInfo != null");
        var ilGenerator = method.GetILGenerator();
        ilGenerator.Emit(OpCodes.Nop);
        ilGenerator.Emit(OpCodes.Ldarg_2);
        ilGenerator.Emit(OpCodes.Dup);
        ilGenerator.Emit(OpCodes.Ldfld, callsFieldInfo);
        ilGenerator.Emit(OpCodes.Ldc_I4_1);
        ilGenerator.Emit(OpCodes.Add);
        ilGenerator.Emit(OpCodes.Stfld, callsFieldInfo);
        return ilGenerator;
    }

    public static implicit operator FunctionWithCounter<T, TResult>(Func<T, TResult> func)
    {
        return new FunctionWithCounter<T, TResult>(func);
    }

    public TResult this[T arg]
    {
        get
        {
            return _functionWithInjection(arg);
        }
    }
}

我的第二个实现基于Emit API,但它太复杂了很长一段时间没有完成......

所以现在这是我的第三次尝试,我想使用表达式。 Шt应该是这样的:

    public FunctionWithCounter(Expression<Func<T, TResult>> function)
    {
        Action action = () => _calls++;
        Expression<Action> closurExpression = () => action();
        var result = Expression.Block(closurExpression, function);
        _functionWithInjection = Expression.Lambda<Func<T,TResult>>(result).Compile();
    }

对不起我的英语,但我真的想实现这个想法

2 个答案:

答案 0 :(得分:5)

好吧,您可以使用Interlocked.Increment来回避规则:

int i = 0;
Expression<Func<bool>> expression = () => Interlocked.Increment(ref i) != 0;

...但我会非常非常谨慎地这样做。考虑到副作用,我不希望处理表达式树的许多代码片段处理得非常干净。

上述似乎工作,就我的行为方式而言:

int i = -2;
Expression<Func<bool>> expression = () => Interlocked.Increment(ref i) != 0;
var del = expression.Compile();
Console.WriteLine(del()); // True
Console.WriteLine(del()); // False
Console.WriteLine(del()); // True
Console.WriteLine(del()); // True
Console.WriteLine(i);     // 2

答案 1 :(得分:2)

我认为您的第一种方法对于简单的非递归案例来说更清晰,更好。 如果你允许你的包装函数知道递归,你可以更进一步,并使包装器成为函数本身的参数:

 class RecursiveFunctionWithCounter<T, TResult> 
 {
    private readonly Func<T, RecursiveFunctionWithCounter<T, TResult>, TResult> function;
    public int Calls { get; set; }

    public RecursiveFunctionWithCounter(Func<T, RecursiveFunctionWithCounter<T, TResult>, TResult> function)
    {
        Calls = 0;
        this.function = function;
    }


    public TResult this[T arg]
    {
        get
        {
            Calls++;
            return function(arg, this);
        }
    }
 }

并像这样使用它:

var rw = new RecursiveFunctionWithCounter<int, int>(
        (n, self) => { return n < 2 ? 1 : n * self[n - 1]; }
);

int rr = rw[3]; // rr=6
int rc = rw.Calls; // rc=3

另一方面,如果您真正想要做的是检测代码中的一些现有方法,请考虑做一点Aspect Oriented Programming(例如PostSharp,这是一个{{3}一个方面,在每个方法调用上递增一个性能计数器)。这样您就可以在方法中添加IncrementPerformanceCounterAttribute之类的属性,AOT库将完成其余的工作。