ilmono.cecil

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


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.


Solution

  • 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)));