【发布时间】:2014-09-04 18:03:20
【问题描述】:
我想写一个闭包并增加它的价值,但我做不到。这是我的代码
int i = 0;
Expression<Func<bool>> closurExpression = () =>
{
i++;
return i != 0;
};
但我收到关于A lambda expression with a statement body cannot be converted to an expression tree 或An 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。所以想法是:获取源函数,并为每次调用方法增量注入调用增量。方法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();
}
对不起我的英语,但我真的很想实现这个想法
【问题讨论】:
-
你真正想要达到什么目的?我已经给出了答案,但这实际上是一个绕过编译器的确切规则同时仍然违反这些规则的精神的情况。
标签: c# .net reflection code-generation linq-expressions