c# - 将 C# 表达式树保存到文件

标签 c# debugging expression debug-symbols

我想调试一个表达式并将表达式树保存到一个文件中:

var generator = DebugInfoGenerator.CreatePdbGenerator();
var document = Expression.SymbolDocument(fileName: "MyDebug.txt");
var debugInfo = Expression.DebugInfo(document, 6, 9, 6, 22);
var expressionBlock = Expression.Block(debugInfo, fooExpression);
var lambda = Expression.Lambda(expressionBlock, parameters);
lambda.CompileToMethod(method, generator);
var bakedType = type.CreateType();
return (type)bakedType.GetMethod(method.Name).Invoke(null, parameters);

如何找到或保存“MyDebug.txt”?

最佳答案

您没有理解SymbolDocument() 是什么...

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 method = type.DefineMethod("go", MethodAttributes.Public | MethodAttributes.Static);

Expression fooExpression = Expression.Divide(Expression.Constant(0), Expression.Constant(0));
var parameters = new ParameterExpression[0];
var generator = DebugInfoGenerator.CreatePdbGenerator();
var document = Expression.SymbolDocument(fileName: "MyDebug.txt");
var debugInfo = Expression.DebugInfo(document, 6, 9, 6, 22);
var expressionBlock = Expression.Block(debugInfo, fooExpression);
var lambda = Expression.Lambda(expressionBlock, parameters);

lambda.CompileToMethod(method, generator);
var bakedType = type.CreateType();
Func<int> method2 = (Func<int>)Delegate.CreateDelegate(typeof(Func<int>), bakedType.GetMethod(method.Name));

try
{
    int res = method2();
}
catch (Exception e)
{
    Console.WriteLine(e.StackTrace);
}

我生成的表达式类似于return 0/0;。我执行它并捕获异常(请注意,我没有使用 Invoke 方法,因为 Invoke 方法会将 DivisionByZeroException 作为InnerException).

我输出的堆栈跟踪是这样的:

在 MyDebug.txt 中的 baz.go() 中:第 6 行 在 ConsoleApplication85.Program.Test()

您看到 MyDebug.txt:row 6 了吗?它们是您的 SymbolDocument 和您的 DebugInfo

一个更完整的例子,取自Debugging Dynamically Generated Code (Reflection.Emit) .

static void Test()
{
    // create a dynamic assembly and module 
    AssemblyName assemblyName = new AssemblyName("HelloWorld");
    AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);

    // Mark generated code as debuggable. 
    // See https://learn.microsoft.com/en-us/archive/blogs/rmbyers/debuggableattribute-and-dynamic-assemblies for explanation.        
    Type daType = typeof(DebuggableAttribute);
    ConstructorInfo daCtor = daType.GetConstructor(new Type[] { typeof(DebuggableAttribute.DebuggingModes) });
    CustomAttributeBuilder daBuilder = new CustomAttributeBuilder(daCtor, new object[] { 
    DebuggableAttribute.DebuggingModes.DisableOptimizations | 
    DebuggableAttribute.DebuggingModes.Default });
    assemblyBuilder.SetCustomAttribute(daBuilder);

    ModuleBuilder module = assemblyBuilder.DefineDynamicModule("HelloWorld.exe", true); // <-- pass 'true' to track debug info.

    var doc = Expression.SymbolDocument(@"Source.txt");

    // create a new type to hold our Main method 
    TypeBuilder typeBuilder = module.DefineType("HelloWorldType", TypeAttributes.Public | TypeAttributes.Class);

    // create the Main(string[] args) method 
    MethodBuilder methodbuilder = typeBuilder.DefineMethod("MyMethod", MethodAttributes.HideBySig | MethodAttributes.Static | MethodAttributes.Public, typeof(void), new Type[] { typeof(string[]) });

    // Create a local variable of type 'string', and call it 'xyz'
    var localXYZ = Expression.Variable(typeof(string), "xyz"); // Provide name for the debugger. 

    var generator = DebugInfoGenerator.CreatePdbGenerator();
    var debugInfo1 = Expression.DebugInfo(doc, 2, 1, 2, 100);

    // Emit sequence point before the IL instructions. This is start line, start col, end line, end column, 

    // Line 2: xyz = "hello"; 
    var assign = Expression.Assign(localXYZ, Expression.Constant("Hello world!"));

    // Line 3: Write(xyz); 
    MethodInfo infoWriteLine = typeof(System.Console).GetMethod("WriteLine", new Type[] { typeof(string) });
    var debugInfo2 = Expression.DebugInfo(doc, 3, 1, 3, 100);

    var write = Expression.Call(infoWriteLine, localXYZ);

    // Line 4: return; 
    var debugInfo3 = Expression.DebugInfo(doc, 4, 1, 4, 100);

    var block = Expression.Block(new ParameterExpression[] { localXYZ }, new Expression[] { debugInfo1, assign, debugInfo2, write, debugInfo3 });
    var lambda = Expression.Lambda<Action<string[]>>(block, Expression.Parameter(typeof(string[])));

    // bake it 
    lambda.CompileToMethod(methodbuilder, generator);
    Type helloWorldType = typeBuilder.CreateType();

    // This now calls the newly generated method. We can step into this and debug our emitted code!! 
    var dm = (Action<string[]>)Delegate.CreateDelegate(typeof(Action<string[]>), helloWorldType.GetMethod("MyMethod"));
    dm(new string[] { null }); // <-- step into this call 
}

将其保存为 Source.txt

1|  // Test
2|  xyz = "hello"; 
3|  Write(xyz); 
4|  return;

然后在dm(new string[] { null })上打断点,在bp上按F11。它会要求您提供 Source.txt。请注意,如果您不选择它,则必须删除 .suo 文件才能再次获取窗口。

请注意 DebuggableAttribute 的使用。似乎是将动态程序集标记为可调试的技巧。

关于c# - 将 C# 表达式树保存到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18813269/

相关文章:

c# - 在同一页面中显示上传的图像 Asp MVC 4 Razor

c++ - 什么预定义宏可用于检测带有 clang 的调试版本?

c++ - 在 C、C++ 或 Objective C 中验证给定的坐标

python - 通过 MetaTrader5 python 模块发送订单以开仓,但没有任何反应

Xcode:在调试时,有什么方法可以阻止它在最前面的窗口中打开导航器?

spring - 特定日期的 Cron 表达式

boolean - 评估 boolean 表达式值的算法

c# - 项目文件不完整。缺少预期的进口

c# - 密码保护数据库

c# - 将 M-V-VM 与 WPF 结合使用,如何在给定 ViewModel 的情况下实例化对话框 View ?