我正在跟进我之前的问题:Mono.Cecil: call base class' method from other assembly 我正在做同样的事情,但如果我的基类是通用的,它就不起作用。
//in Assembly A
class BaseVM<T> {}
//in Assembly B
class MyVM : Base<SomeModel> {
[NotifyProperty]
public string Something {get;set;}
}
编织以下代码:
L_000e: call instance void [AssemblyA]Base`1::RaisePropertyChanged(string)
而不是
L_000e: call instance void [AssemblyA]Base`1<class SomeModel>::RaisePropertyChanged(string)
有什么可以改变的?
答案 0 :(得分:20)
在上一篇文章中,您表明您使用的代码如下:
TypeDefinition type = ...;
TypeDefintion baseType = type.BaseType.Resolve ();
MethodDefinition baseMethod = baseType.Methods.First (m => ...);
MethodReference baseMethodReference = type.Module.Import (baseMethod);
il.Emit (OpCodes.Call, baseMethodReference);
显然,这不适用于泛型:
当Resolve ()
.BaseType时,您将丢失通用实例化信息。您需要使用基类型中的适当通用信息重新创建适当的方法调用。
为简化起见,让我们使用以下方法,取自Cecil测试套件:
public static TypeReference MakeGenericType (this TypeReference self, params TypeReference [] arguments)
{
if (self.GenericParameters.Count != arguments.Length)
throw new ArgumentException ();
var instance = new GenericInstanceType (self);
foreach (var argument in arguments)
instance.GenericArguments.Add (argument);
return instance;
}
public static MethodReference MakeGeneric (this MethodReference self, params TypeReference [] arguments)
{
var reference = new MethodReference(self.Name,self.ReturnType) {
DeclaringType = self.DeclaringType.MakeGenericType (arguments),
HasThis = self.HasThis,
ExplicitThis = self.ExplicitThis,
CallingConvention = self.CallingConvention,
};
foreach (var parameter in self.Parameters)
reference.Parameters.Add (new ParameterDefinition (parameter.ParameterType));
foreach (var generic_parameter in self.GenericParameters)
reference.GenericParameters.Add (new GenericParameter (generic_parameter.Name, reference));
return reference;
}
有了这些,您可以将代码重写为:
TypeDefinition type = ...;
TypeDefintion baseTypeDefinition = type.BaseType.Resolve ();
MethodDefinition baseMethodDefinition = baseTypeDefinition.Methods.First (m => ...);
MethodReference baseMethodReference = type.Module.Import (baseMethodDefinition);
if (type.BaseType.IsGenericInstance) {
var baseTypeInstance = (GenericInstanceType) type.BaseType;
baseMethodReference = baseMethodReference.MakeGeneric (baseTypeInstance.GenericArguments.ToArray ());
}
il.Emit (OpCodes.Call, baseMethodReference);