【问题标题】:adding a new constructor to "existing" type with mono.cecil使用 mono.cecil 向“现有”类型添加新构造函数
【发布时间】:2012-12-13 17:58:15
【问题描述】:

我正在尝试将新的重载构造函数添加到现有类型。 我尝试使用 emit 命名空间来做到这一点,但是创建的类型不会继承基类和所有其他方法。

在阅读了一些文章后,我认为 .net 框架内置类是不可能的。

所以我得到了 Mono.Cecil,但找不到任何体面的例子来实现这一点。

我遇到了一个复制方法的示例,但不复制道具、字段等。

【问题讨论】:

  • 您能解释一下您为什么要这样做吗?你说的是哪种类型?另外,你试过什么?那是怎么失败的?
  • public class Parent : Child { public Parent(int x, int y) : base(x, y) { } //other stuff } 基本上,我正在尝试添加这个构造函数。我试过这样的事情:msdn.microsoft.com/en-us/library/… 但是在调用新的构造函数之后,对象不是从 Child 类继承的,而是从对象类本身继承的。但是,基本构造函数在调试中被调用。发出代码是这样的:(忽略 cecil 约定)
  • ctorIL.Append(ctorIL.Create(Mono.Cecil.Cil.OpCodes.Ldarg_0)); ctorIL.Append(ctorIL.Create(Mono.Cecil.Cil.OpCodes.Ldarg_1)); ctorIL.Append(ctorIL.Create(Mono.Cecil.Cil.OpCodes.Ldarg_2)); ctorIL.Append(ctorIL.Create(Mono.Cecil.Cil.OpCodes.Call, baseMethod)); ctorIL.Append(ctorIL.Create(Mono.Cecil.Cil.OpCodes.Ret));
  • 所以现在,我要尝试这样的事情: -Hook Assembly.Resolve 事件 -查找从 Child 继承的类型 -使用 Mono.Cecil 为每种类型添加构造函数 -将新程序集写入文件 -加载新的程序集文件我在正确的路径吗?还是有其他方法可以做到这一点?

标签: reflection reflection.emit mono.cecil


【解决方案1】:

这增加了一个空的构造函数

void AddEmptyConstructor(TypeDefinition type, MethodReference baseEmptyConstructor)
{
    var methodAttributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName;
    var method = new MethodDefinition(".ctor", methodAttributes, ModuleDefinition.TypeSystem.Void);
    method.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0));
    method.Body.Instructions.Add(Instruction.Create(OpCodes.Call, baseEmptyConstructor));
    method.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
    type.Methods.Add(method);
}

您需要对其进行扩展以传递额外的参数。

来自here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-16
    • 2012-05-04
    • 1970-01-01
    • 2019-07-21
    相关资源
    最近更新 更多