使用Mono Cecil注入属性调用

时间:2010-11-23 22:29:50

标签: c# .net mono.cecil

如何将此代码注入方法Test()

this.DialogResult = DialogResult.OK;

因此注入后的方法如下所示:

public void Test()
{
this.DialogResult = DialogResult.OK;
}

1 个答案:

答案 0 :(得分:3)

这将在Test方法的顶部插入赋值,前提是DialogResult字段在声明Test的相同类型中声明(否则你将不得不浏览它的层次结构来检索它):

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));