我正在使用Mono.Cecil
(版本 0.6.9.0)为实现接口方法的方法设置别名。为此,我必须Override
在目标方法中添加一个指向接口方法的方法(很像 VB.NET 的可能性),如下所示:
using System;
using System.Reflection;
using Mono.Cecil;
class Program {
static void Main(string[] args) {
var asm = AssemblyFactory.GetAssembly(Assembly.GetExecutingAssembly().Location);
var source = asm.MainModule.Types["A"];
var sourceMethod = source.Methods[0];
var sourceRef = new MethodReference(
sourceMethod.Name,
sourceMethod.DeclaringType,
sourceMethod.ReturnType.ReturnType,
sourceMethod.HasThis,
sourceMethod.ExplicitThis,
sourceMethod.CallingConvention);
var target = asm.MainModule.Types["C"];
var targetMethod = target.Methods[0];
targetMethod.Name = "AliasedMethod";
targetMethod.Overrides.Add(sourceRef);
AssemblyAssert.Verify(asm); // this will just run PEVerify on the changed assembly
}
}
interface A {
void Method();
}
class C : A {
public void Method() { }
}
我得到的是一个PEVerify.exe
错误,表明我的类不再实现接口方法。覆盖引用和接口中的方法之间的更改程序集似乎存在令牌不匹配:
[MD]: Error: Class implements interface but not method (class:0x02000004; interface:0x02000002; method:0x06000001). [token:0x09000001]
我知道如果我MethodDefinition
直接使用它会起作用:
targetMethod.Overrides.Add(sourceMethod);
但我真的需要使用 aMethodReference
因为我可能在所涉及的类型中有泛型参数和参数,而简单的MethodDefinition
不会这样做。
更新:根据Jb Evain的建议,我已迁移到 0.9.3.0 版。但是,同样的错误仍然发生。这是迁移的代码:
var module = ModuleDefinition.ReadModule(Assembly.GetExecutingAssembly().Location);
var source = module.GetType("A");
var sourceMethod = source.Methods[0];
var sourceRef = new MethodReference(
sourceMethod.Name,
sourceMethod.ReturnType) {
DeclaringType = sourceMethod.DeclaringType,
HasThis = sourceMethod.HasThis,
ExplicitThis = sourceMethod.ExplicitThis,
CallingConvention = sourceMethod.CallingConvention
};
var target = module.GetType("C");
var targetMethod = target.Methods[0];
targetMethod.Name = "AliasedMethod";
targetMethod.Overrides.Add(sourceRef);