我有一个生成的lambda,但是当我想观看它时,就像普通的lambda一样,它什么也没显示。当我呼叫expr.Body.ToString()
时,我得到以下信息:
{var compareA; ... }
但是用于表达的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:
}
}
为什么我得到这个结果?
最佳答案
这是因为Expression.ToString
覆盖依赖于内部ExpressionStringBuilder
访问者类型,该访问者类型会大大简化表达式树的表示形式。
如您所知,通过对每个Expression
派生的类型(即[DebuggerTypeProxy(typeof(Expression.BlockExpressionProxy))]
上的BlockExpression
)定义的自定义调试器代理提供的调试视图通过暴露更详细的访问者(也是内部的)。
不幸的是,除非您愿意使用反射来获取私有DebugViewWriter
属性(在DebugView
中定义)的值,否则无法在调试方案之外轻松获得该输出,如下所示:
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);
产生
.Lambda #Lambda1<System.Func`2[System.String,System.Int32]>(System.String $str) {
$str.Length
}
与往常一样,参考资料来源是您最好的朋友:
http://referencesource.microsoft.com/#System.Core/Microsoft/Scripting/Ast/Expression.cs,aa5f054356a8a17d