C# 如何将接口方法实现与Mono.Cecil别名?
我正在使用C# 如何将接口方法实现与Mono.Cecil别名?,c#,mono.cecil,C#,Mono.cecil,我正在使用Mono.Cecil(版本0.6.9.0)来别名一个实现接口方法的方法。为此,我必须向目标方法添加一个覆盖,该方法指向接口方法(非常类似于VB.NET的功能),如下所示: using System; using System.Reflection; using Mono.Cecil; class Program { static void Main(string[] args) { var asm = AssemblyFactory.GetAssembly(Assemb
Mono.Cecil
(版本0.6.9.0)来别名一个实现接口方法的方法。为此,我必须向目标方法添加一个覆盖
,该方法指向接口方法(非常类似于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);
但是我确实需要使用MethodReference
,因为我可能在涉及的类型中有泛型参数和参数,而简单的MethodDefinition
就不行了
更新:根据的建议,我已经升级到版本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);
这是使用0.6的烦恼之一。您必须将新创建的MethodReference放入模块的.MemberReferences集合中
我强烈建议您切换到0.9。非常感谢,但我也尝试过,但没有成功。我刚刚迁移了它,但也遇到了同样的错误。我会更新这个问题。乔丹·多:对我来说,这似乎是一个臭虫。方法引用已正确发出,但peverify不喜欢它。如果我使用您的确切场景,但使用泛型类型上的方法,它就可以正常工作。因此,在我看来,您必须自己处理它,也就是说,如果方法不在泛型类型上并且是在当前程序集中定义的,则将MethodDefinition放入,否则您将创建MethodReference。它对我有效!非常感谢你的回答和神奇的图书馆!您知道没有使用PEVerify验证程序集(可能在Mono项目中)的任何编程方式吗?