扭转前pression< Func键< T,TResult>> .Compile()?Func、LT、pression、Compile

2023-09-02 21:46:15 作者:妖孽范儿

因为我们可以:

Expression<Func<int, bool>> predicate = x => x > 5;
var result = Enumerable.Range(0,10).Where(predicate.Compile());

如何:

Func<int,bool> predicate = x => x > 5;
Expression<Func<int,bool>> exp = predicate.Decompile();

这就是我想要得到相应的防爆pression的 Func键。这可能吗?

That is, I want to get the corresponding Expression of the Func. Is it possible?

推荐答案

有没有神奇的反编译()的代表的情况下,短的解构IL(也许Mono.Cecil能做到)。如果你想要一个EX pression树,你得的启动的和前pression树,所以有防爆pression&LT; Func键&LT; INT ,布尔&GT;&GT; througout

There is no magic Decompile() for a delegate instance, short of deconstructing the IL (perhaps with mono.cecil). If you want an expression tree, you'll have to start with an expression tree, so have Expression<Func<int, bool>> througout.

作为一个边缘的情况下,你可以得到的基本的距离的方法委托信息的委托的。方法(即 MethodInfo的)和 .TARGET (即为arg0 ) - 然而,对于涉及拉姆达大多数情况下,或匿名方法,这将指向上采集类的编译器生成的方法,所以不会真正帮助你多少。这是pretty的多局限于场景,如:

As an edge case, you can get basic method delegate information from the delegate's .Method (the MethodInfo) and .Target (the arg0) - however, for most scenarios involving a lambda or anonymous method this will point at the compiler-generate method on the capture class, so won't really help you much. It is pretty much limited to scenarios like:

Func<string,int> parse = int.Parse;