【问题标题】:Expression.DebugInfo How Do I Tag Expressions?Expression.DebugInfo 如何标记表达式?
【发布时间】:2011-07-20 22:05:15
【问题描述】:

所以我知道 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(" ");
        }
    }
}

我知道调试信息仅适用于已编译的方法,所以这就是我动态生成程序集的原因。但是当这段代码导致“除以零”错误时,它不会显示我的“TestDebug.txt”文件

【问题讨论】:

    标签: c# linq debugging reflection.emit


    【解决方案1】:

    看来我错过了调试信息生成器。需要添加此代码:

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

    它现在就像一个魅力!

    【讨论】:

      猜你喜欢
      • 2019-02-22
      • 2017-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-28
      • 1970-01-01
      • 2018-08-06
      相关资源
      最近更新 更多