从表达式树中获取函数信息

问题描述 投票:0回答:0

出于记录目的,我想自动捕获我代码中调用的函数并将它们保存为字符串以写在我的日志中。

如果我只使用普通的 lambda,这会很好地工作,例如:

Expression<Func<double, bool>> lambda = x => x < 0;
Console.WriteLine(lambda.Parameters[0].Name);
Console.WriteLine(lambda.Body);

我得到:

x

(×< 0)

但是如果我用其他的变量,就显得不方便了:

int factor = 2;
Expression<Func<double, bool>> lambda = x => x * factor < 0;
Console.WriteLine(lambda.Parameters[0].Name);
Console.WriteLine(lambda.Body);

这将给:

x

((x * Convert(值(MyProg.Program+<>c__DisplayClass0_0).factor)) < 0)

原则上,我可以从这个正则表达式中得到像 x * factor 这样的结果< 0, but is there a better way to achieve this?

c# expression-trees
© www.soinside.com 2019 - 2024. All rights reserved.