2

I have a problem with this code :

public static Delegate[] ExtractMethods(object obj)
{
    Type type = obj.GetType();
    MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
    Delegate[] methodsDelegate = new Delegate[methods.Count()];

    for (int i = 0; i < methods.Count(); i++)
    {
        methodsDelegate[i] = Delegate.CreateDelegate(null, methods[i]);
    }
    return methodsDelegate;
}

at Delegate.CreateDelegate delegate type most drived but I call this method for several objects. How to get delegate type ?

moien
  • 999
  • 11
  • 26

2 Answers2

5

It worked for me. [ https://stackoverflow.com/a/16364220/1559611 ]

    public static Delegate[] ExtractMethods(object obj)
    {
        Type type = obj.GetType();

        MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);

        Delegate[] methodsDelegate = new Delegate[methods.Count()];

        for (int i = 0; i < methods.Count(); i++)
        {
            methodsDelegate[i] = CreateDelegate(obj , methods[i]);
        }

        return methodsDelegate;
    }

    public static Delegate CreateDelegate(object instance, MethodInfo method)
    {
        var parameters = method.GetParameters()
                   .Select(p => Expression.Parameter(p.ParameterType, p.Name))
                    .ToArray();

        var call = Expression.Call(Expression.Constant(instance), method, parameters);
        return Expression.Lambda(call, parameters).Compile();
    }
Community
  • 1
  • 1
moien
  • 999
  • 11
  • 26
1

Use MethodInfo.DeclaringType

Type type = methods[0].DeclaringType;

you will have to be bit careful if you are using inheritance.

Also have a look at MethodInfo.ReflectedType

Miguel Sanchez
  • 434
  • 3
  • 11