查看从编译表达式生成的IL代码
收藏

在表达式树上调用Compile()时,是否可以查看生成的IL代码?考虑这个非常简单的示例:

class Program
{
    public int Value { get; set; }

    static void Main(string[] args)
    {
        var param = Expression.Parameter(typeof(Program));
        var con = Expression.Constant(5);
        var prop = Expression.Property(param, typeof(Program).GetProperty("Value"));
        var assign = Expression.Assign(prop, con);
        Action<Program> lambda = Expression.Lambda<Action<Program>>(assign, param).Compile();

        Program p = new Program();
        lambda(p);



        //p.Value = 5;
    }
}

Now, the expression tree does what the last line of Main says. Compile the application, then open it in Reflector. You can see the IL code of p.Value = 5; that does the assignment. But the expression tree was made and compiled at runtime. Is it possible to view the resulting IL code from the compile?

最佳答案

是!使用此工具:

https://github.com/drewnoakes/il-visualizer

我相信您可以想象,这在实现和调试Compile时非常有用。

    公众号
    关注公众号订阅更多技术干货!