Expression.DebugInfo如何标记表达式?

所以我知道Expression.DebugInfo用于什么,我创建了一个Debug表达式,但是如何用这个调试信息标记其他表达式? 这是我正在尝试的一个非常基本的测试:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Linq.Expressions; using System.Reflection; namespace ExpressionDebugTest { class Program { static void Main(string[] args) { var asm = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("foo"), System.Reflection.Emit.AssemblyBuilderAccess.RunAndSave); var mod = asm.DefineDynamicModule("mymod", true); var type = mod.DefineType("baz", TypeAttributes.Public); var meth = type.DefineMethod("go", MethodAttributes.Public | MethodAttributes.Static); var sdi = Expression.SymbolDocument("TestDebug.txt"); var di = Expression.DebugInfo(sdi, 2, 2, 2, 12); var exp = Expression.Divide(Expression.Constant(2), Expression.Subtract(Expression.Constant(4), Expression.Constant(4))); var block = Expression.Block(di, exp); Expression.Lambda(block, new ParameterExpression[0]).CompileToMethod(meth); var newtype = type.CreateType(); asm.Save("tmp.dll"); newtype.GetMethod("go").Invoke(null, new object[0]); //meth.Invoke(null, new object[0]); //lambda.DynamicInvoke(new object[0]); Console.WriteLine(" "); } } } 

我知道Debug信息只适用于编译方法,所以这就是为什么我要动态生成一个程序集。 但是当这段代码导致“除以零”错误时,它没有显示我的“TestDebug.txt”文件

所以我似乎错过了调试信息生成器。 需要添加此代码:

  var gen = DebugInfoGenerator.CreatePdbGenerator(); Expression.Lambda(block, new ParameterExpression[0]).CompileToMethod(meth,gen); 

它现在就像一个魅力!