How to create an override method using Mono.Cecil?

拈花ヽ惹草 提交于 2019-11-30 18:42:39
Jb Evain

In your base class, let's say you generate the following method:

public virtual void f(int);

You have to make sure that it has the flag IsVirtual set to true. You also have to make sure that it has the flag IsNewSlot = true, to make sure that it has a new slot in the virtual method table.

Now, for the overridden methods, you want to generate:

public override void f(int);

To do so, you also need to have the method to be IsVirtual, but also to tell it that it's not a new virtual method, but that it implicitly overrides another, so you have to make it .IsReuseSlot = true.

And because you're using implicit overriding, you also have to make sure both methods are .IsHideBySig = true.

With that all set, you should have a proper overriding method.

For the benefit of other readers, here is the final result obtained by following JB's answer:

void CreateMethodOverride(TypeDefinition targetType,
    TypeDefinition baseClass, string methodName, MethodInfo methodInfo)
{
    MethodDefinition baseMethod = baseClass
        .Methods.First(method => method.Name.Equals(methodName));

    MethodDefinition newMethod = targetType.Copy(methodInfo);
    newMethod.Name = baseMethod.Name;

    // Remove the 'NewSlot' attribute
    newMethod.Attributes = baseMethod.Attributes & ~MethodAttributes.NewSlot;

    // Add the 'ReuseSlot' attribute
    newMethod.Attributes |= MethodAttributes.ReuseSlot;

    newMethod.ImplAttributes = baseMethod.ImplAttributes;
    newMethod.SemanticsAttributes = baseMethod.SemanticsAttributes;
    targetType.Methods.Add(newMethod);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!