如何在运行时删除emit il的最后几段
我试图在一千行代码中修改一些逻辑,我想用rollback-il方式添加新的逻辑,避免更改以前的代码。
简单的,例如:
我希望删除emit il的最后几段,然后在
isSomeLogic
是真的。
void Main()
{
DynamicMethod methodbuilder = new DynamicMethod("Deserialize" + Guid.NewGuid().ToString(), typeof(void), null);
var il = methodbuilder.GetILGenerator();
il.Emit(OpCodes.Ldstr, "Hello World");
Type[] types = new Type[1]{typeof(string)};
MethodInfo method = typeof(Console).GetMethod("WriteLine", types);
il.Emit(OpCodes.Call, method);
il.Emit(OpCodes.Ret);
// do some thing...
var isSomeLogic = true;
if( isSomeLogic ){
//remove the il OpCodes.Ret and add new logic Emit
il.Emit(OpCodes.Ret);
}
var func = (Action)methodbuilder.CreateDelegate(typeof(Action));
func();
}