Reputation: 63
I have the following code, using Mono.Cecil:
{
ModuleDefinition module = ModuleDefinition.ReadModule("library.dll");
TypeDefinition type1 = module.Types.Where(t => "Namespace.Destination".Equals(t.FullName)).Single();
TypeDefinition type2 = module.Types.Where(t => "Namespace.Target".Equals(t.FullName)).Single();
MethodDefinition method1 = type1.Methods.Where(m => "Test".Equals(m.Name)).Single();
MethodDefinition method2 = type2.Methods.Where(m => "Test".Equals(m.Name)).Single();
var processor = methodTesta1.Body.GetILProcessor();
var newInstruction = processor.Create(OpCodes.Call, methodTesta2);
var firstInstruction = methodTesta1.Body.Instructions[0];
processor.Replace(firstInstruction, newInstruction);
}
namespace Namespace
{
public class Destination
{
public String Test()
{
Console.Write("Destination method");
}
}
public class Target
{
public String Test()
{
Console.Write("Target Method");
}
}
}
I'd not like to create a new "dll" file or overwrite the current, I want to modify class only at runtime. How can I "persist" the modification and create a new instance of Destination class with modified method? Is there a way to do it?
EDIT: The objective is execute a different method body, when certain method is called, which return a certain type.
Upvotes: 0
Views: 200