Mono.Cecil入门示例:如何获取方法体(MethodBody)
Using Mono.Cecil to Get MethodBody and Output Readable IL Instructions
Got it, let's break this down for you! As someone new to Mono.Cecil, it's easy to get stuck with the pseudo-code approach—here's a complete, working example that grabs the MethodBody of your HelloWorld method and outputs its IL instructions as a readable string.
First, Install Mono.Cecil
Before writing code, make sure you install the Mono.Cecil NuGet package in your project:
- Use the Package Manager Console:
Install-Package Mono.Cecil - Or search for "Mono.Cecil" in your IDE's NuGet package manager and install it.
Complete Working Example
using System; using System.Linq; using System.Windows.Forms; using Mono.Cecil; using Mono.Cecil.Cil; namespace my { public class MainClass { [STAThread] static void Main(string[] args) { // Get the path to the currently running assembly string assemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location; // Load the assembly with Mono.Cecil using (AssemblyDefinition assembly = AssemblyDefinition.ReadAssembly(assemblyPath)) { // Find our target class (my.MainClass) TypeDefinition targetType = assembly.MainModule.Types.First(t => t.FullName == "my.MainClass"); // Find the HelloWorld method MethodDefinition helloMethod = targetType.Methods.First(m => m.Name == "HelloWorld"); // Check if the method has a body (some methods like abstract ones don't) if (helloMethod.HasBody) { Console.WriteLine("=== IL Instructions for HelloWorld Method ==="); // Iterate over each IL instruction and print it foreach (Instruction instruction in helloMethod.Body.Instructions) { // Instruction.ToString() gives a readable format: OpCode + Operand (if any) // We add the offset in hex for clarity Console.WriteLine($"0x{instruction.Offset:X4}: {instruction}"); } } else { Console.WriteLine("HelloWorld method has no body!"); } } // Optional: Test the actual method works new MainClass().HelloWorld(); Console.ReadLine(); } public void HelloWorld() { MessageBox.Show("Hiiiiiiiiii"); } } }
Key Explanations
- Loading the Assembly: Mono.Cecil works by reading the compiled assembly file, not directly from the runtime type. We use
AssemblyDefinition.ReadAssembly()to load our own running assembly here. - Accessing MethodBody: Instead of calling
GetMethodBody().ToString()(which doesn't output useful IL), we iterate overhelloMethod.Body.Instructions. EachInstructionobject has a built-inToString()that gives a human-readable version of the IL opcode and operand. - Type/Method Lookup: We use LINQ's
First()to find our target class and method—make sure the full names match exactly (including namespace) to avoid errors. - STAThread Attribute: Required if you're using
MessageBox(from Windows Forms) to avoid threading issues.
Output Preview
When you run the program, you'll see output like this in the console:
=== IL Instructions for HelloWorld Method === 0x0000: ldstr "Hiiiiiiiiii" 0x0005: call System.Void System.Windows.Forms.MessageBox::Show(System.String) 0x000A: ret
This is the actual IL code that executes when HelloWorld() is called—super useful for understanding what your code is doing under the hood!
内容的提问来源于stack exchange,提问作者T.Todua
相关产品推荐
相关产品推荐

