gpt4 book ai didi

c# - 表达式的增量值

转载 作者:太空宇宙 更新时间:2023-11-03 18:29:53 25 4
gpt4 key购买 nike

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

        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。所以想法是:获取源函数,并为每次方法调用增加调用注入(inject)增量。方法的所有内部调用 somefunc应该用我们的方法代替funcWithInjection ,在这种情况下,我们也会捕获递归函数。这是我的代码,但它不起作用(除了注入(inject),所以这段代码确实增加了一个字段值,但我不能将源的方法体添加到尾部并编译它,如果你愿意,你可以玩它):

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();
}

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

最佳答案

好吧,您可以使用 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

关于c# - 表达式的增量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24743018/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com