简体   繁体   English

Mono.Cecil - 如何获取方法体的简单示例

[英]Mono.Cecil - simple example how to get method body

I have been searching for a newbie question, but can't find a simple example.我一直在寻找一个新手问题,但找不到一个简单的例子。 Can anyone give me a simple example how to get MethodBody into most available string result?谁能给我一个简单的例子,如何将 MethodBody 放入最可用的字符串结果中? Like:像:

using Mono.Cecil;
using Mono.Cecil.Cil;

namespace my
{
    public class Main
    {
        public Main()
        {
             // phseudo code, but doesnt work
            Console.Write(    getMethod("HelloWorld").GetMethodBody().ToString()   );
        }

        public void HelloWorld(){
             MessageBox.Show("Hiiiiiiiiii");
        }
    }
}

Start with reading your assembly:从阅读你的程序集开始:

var path = "... path to your assembly ...";
var assembly = AssemblyDefinition.ReadAssembly(path);

You can use System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName as path if you want to open running process如果要打开正在运行的进程,可以使用System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName作为path

Now get all types and methods wich you want to inspect现在获取您想要检查的所有类型和方法

var toInspect = assembly.MainModule
  .GetTypes()
  .SelectMany(t => t.Methods
      .Where(m => m.HasBody)
      .Select(m => new {t, m}))
  

If you already knew type and method names you can modify your query something like this:如果您已经知道类型和方法名称,您可以像这样修改您的查询:

toInspect = toInspect.Where(x => x.t.Name.EndsWith("Main") && x.m.Name == "HelloWorld");

After that just iterate over that collection:之后只需迭代该集合:

foreach (var method in toInspect)
{
    Console.WriteLine($"\tType = {method.t.Name}\n\t\tMethod = {method.m.Name}");
    foreach (var instruction in method.m.Body.Instructions)
        Console.WriteLine($"{instruction.OpCode} \"{instruction.Operand}\"");
}

Output will be输出将是

Type = Main
  Method = HelloWorld

ldstr "Hiiiiiiiiii"
call "System.Windows.Forms.DialogResult System.Windows.Forms.MessageBox::Show(System.String)"
pop ""
ret ""

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM