Reflection.Emit: How to reliably convert a MethodBuilder to RuntimeMethodInfo?

After generating the type dynamically and calling TypeBuilder.CreateType, I want to create a delegate that points to a method in the new type. But if I use code like

loadedType = typeBuilder.CreateType();
myDelegate = (MyDelegate)Delegate.CreateDelegate(
                                  typeof(MyDelegate), methodBuilder);

Reusing the Builder method as anInfo method, I get the exception "MethodInfo must be RuntimeMethodInfo". Now, as a rule, I can re-get MethodInfo using

MethodInfo mi = loadedType.GetMethod(methodBuilder.Name);
myDelegate = (MyDelegate)Delegate.CreateDelegate(typeof(MyDelegate), mi);

But my class may contain several overloaded methods with the same name. How can I make the right choice? Do the methods have some constant identifier that I could find in loadType?

Update: OK, this is what I use to re-acquire MethodInfo. I just want to make sure that it works in all cases.

private static MethodInfo ReacquireMethod(Type type, MethodInfo method)
{
    BindingFlags flags = BindingFlags.DeclaredOnly;
    flags |= (method.IsPublic ? BindingFlags.Public : BindingFlags.NonPublic);
    flags |= (method.IsStatic ? BindingFlags.Static : BindingFlags.Instance);
    MethodInfo m = type.GetMethod(method.Name, flags, null,
                                          ParameterTypes(method), null);
    Debug.Assert(m != null);
    return m;
}
+3
2

, .

, , GetParameters methodBuilder, ParameterInfo[] Type[], GetMethod :

MethodInfo mi = loadedType.GetMethod(
    methodBuilder.Name,
    methodBuilder.GetParameters().Select(p => p.ParameterType).ToArray());
+3

GetMethod, . . , , MethodInfo:

Type.GetMethod(String, Type [])

:

MethodInfo mi = loadedType.GetMethod(
    methodBuilder.Name, 
    new[] 
    { 
        typeof(string), 
        typeof(int) 
    }
);

assillingBuilder.Name - "MyMethod", :

public <returnType> MyMethod(string param1, int param2);

, , .

0

Source: https://habr.com/ru/post/1749779/


All Articles