Expression.ToString() 工作吗?

Ale*_*kiy 2 .net c# lambda linq-expressions

我有一个生成的 lambda,但是当我想观看它时,它就像一个普通的 lambda,它只是不显示任何内容。当我打电话时,expr.Body.ToString()我得到以下信息:

{var compareA; ... }
Run Code Online (Sandbox Code Playgroud)

但是用于表达式的 DebugView 工作正常:

.Lambda #Lambda1<System.Comparison`1[XLinq.Test.Comparers.CustomComparerTest+Test]>(
    XLinq.Test.Comparers.CustomComparerTest+Test $x,
    XLinq.Test.Comparers.CustomComparerTest+Test $y) {
    .Block(System.Int32 $compareA) {
        $compareA = .Call ($x.A).CompareTo($y.A);
        .If ($compareA != 0) {
            .Return #Label1 { $compareA }
        } .Else {
            .Block(System.Int32 $compareB) {
                $compareB = .Call ($x.B).CompareTo($y.B);
                .If ($compareB != 0) {
                    .Return #Label1 { $compareB }
                } .Else {
                    .Block(System.Int32 $compareC) {
                        $compareC = .Call ($x.C).CompareTo($y.C);
                        .If ($compareC != 0) {
                            .Return #Label1 { $compareC }
                        } .Else {
                            .Block(System.Int32 $compareD) {
                                $compareD = .Call ($x.D).CompareTo($y.D);
                                .If ($compareD != 0) {
                                    .Return #Label1 { $compareD }
                                } .Else {
                                    .Default(System.Void)
                                }
                            }
                        }
                    }
                }
            }
        };
        .Label
            0
        .LabelTarget #Label1:
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么我得到这个结果?

Kir*_*kiy 5

这是因为Expression.ToString覆盖依赖于内部ExpressionStringBuilder访问者类型,这会产生一个大大简化的表达式树表示。

正如您发现的那样,由定义在每个Expression派生类型(即[DebuggerTypeProxy(typeof(Expression.BlockExpressionProxy))]on BlockExpression)上的自定义调试器代理提供的调试视图通过公开更详细的DebugViewWriter访问者(也是内部访问者)的输出提供了更多信息。

不幸的是,您无法在调试场景之外轻松获得该输出,除非您愿意使用反射来获取私有DebugView属性(在 中定义System.Linq.Expressions.Expression)的值,如下所示:

Expression<Func<string, int>> expr = str => str.Length;
BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
PropertyInfo debugViewProp = typeof(Expression).GetProperty("DebugView", flags);
MethodInfo debugViewGetter = debugViewProp.GetGetMethod(nonPublic: true);
string debugView = (string)debugViewGetter.Invoke(expr, null);
Run Code Online (Sandbox Code Playgroud)

生产

.Lambda #Lambda1<System.Func`2[System.String,System.Int32]>(System.String $str) {
    $str.Length
}
Run Code Online (Sandbox Code Playgroud)

一如既往,参考源是您最好的朋友:

http://referencesource.microsoft.com/#System.Core/Microsoft/Scripting/Ast/Expression.cs,aa5f054356a8a17d