Expression.DebugInfo How Do I Tag Expressions?

夙愿已清 提交于 2019-12-07 00:39:37

问题


So I know what Expression.DebugInfo is used for, and I have an Debug expression created, but how to I tag other expressions with this debug info? Here's what I'm trying as a really basic test:

    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(" ");
        }
    }
}

I know Debug info only works for compiled methods so that's why I'm generating an assembly on the fly. But when this code causes a "divide by zero" error, it's not showing my my "TestDebug.txt" file


回答1:


So it seems I was missing the debug info generator. This code needed to be added:

    var gen = DebugInfoGenerator.CreatePdbGenerator();

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

It works like a charm now!



来源:https://stackoverflow.com/questions/6769122/expression-debuginfo-how-do-i-tag-expressions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!