问题描述
我一直在寻找一个新手问题,但找不到一个简单的例子.谁能给我一个简单的例子,如何将 MethodBody 放入最可用的字符串结果中?喜欢:
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? 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);
如果你想打开正在运行的进程,你可以使用System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName
作为path
You can use System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName
as path
if you want to open running process
现在获取您想要检查的所有类型和方法
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");
之后只需遍历该集合:
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}\"");
}
输出将是
Type = Main
Method = HelloWorld
ldstr "Hiiiiiiiiii"
call "System.Windows.Forms.DialogResult System.Windows.Forms.MessageBox::Show(System.String)"
pop ""
ret ""
这篇关于Mono.Cecil - 如何获取方法体的简单示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!