How can I use Mono.Cecil to call a generic method

947 views Asked by At

I'm trying to import a method and its IL code like
callvirt instance !!0 [UnityEngine]UnityEngine.GameObject::AddComponent<class RealMono>()
The RealMono is a MonoBehavior which I created .
I have no idea to get the generic method.

1

There are 1 answers

0
KyleCTX On BEST ANSWER

It works!!

using System.Reflection;

...

MemberInfo[] ms = typeof(GameObject).GetMember("AddComponent*", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance);
MethodInfo mm = null;
foreach(MemberInfo m in ms) {
    if (((MethodInfo)m).IsGenericMethod) {
        mm = (MethodInfo)m;
        mm = mm.MakeGenericMethod(mm);
        break;
    }
}
il.InsertBefore(method.Body.Instructions[0], il.Create(OpCodes.Callvirt, assembly.MainModule.Import(mm)));