Mono.Cecil: calling a GENERIC base class method from another assembly

I follow my previous question: Mono .Cecil: calling a base class method from another assembly .
I am doing the same thing, but if my base class is generic, it does not work.

//in Assembly A
class BaseVM<T> {}

//in Assembly B
class MyVM : Base<SomeModel> {
 [NotifyProperty]
 public string Something {get;set;}
}

It binds the following code:

L_000e: call instance void [AssemblyA]Base`1::RaisePropertyChanged(string)

instead

L_000e: call instance void [AssemblyA]Base`1<class SomeModel>::RaisePropertyChanged(string)

What needs to be changed?

+5
source share
1 answer

In a previous post, you indicate that you are using the code:

TypeDefinition type = ...;
TypeDefintion baseType = type.BaseType.Resolve ();
MethodDefinition baseMethod = baseType.Methods.First (m => ...);
MethodReference baseMethodReference = type.Module.Import (baseMethod);
il.Emit (OpCodes.Call, baseMethodReference);

Obviously this is not suitable for generics:

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);
+16

All Articles