Inject property call with Mono Cecil
How can I inject开发者_高级运维 this code into the method Test()
?
this.DialogResult = DialogResult.OK;
So the method after injecting will look like this:
public void Test()
{
this.DialogResult = DialogResult.OK;
}
That will insert the assignment at the top of the Test method, provided that the field DialogResult is declared in the same type declaring Test (otherwise you'll have to browse its hierarchy to retrieve it):
var module = ModuleDefinition.ReadModule ("assembly.dll");
var container = module.GetType ("Container");
var test = container.Methods.First (m => m.Name == "Test");
var field = container.Fields.First (f => f.Name == "DialogResult");
var il = test.Body.GetILProcessor ();
var first = test.Body.Instructions [0];
il.InjectBefore (first, il.Create (OpCodes.Ldarg_0));
il.InjectBefore (first, il.Create (OpCodes.Ldc_i4, (int) DialogResult.Ok));
il.InjectBefore (first, il.Create (OpCodes.Stfld, field));
精彩评论