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 ?

2 Answers 2

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();
    }
1
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

5
  • I get error for both -> Type must derive from Delegate.
    – moien
    Oct 14, 2016 at 6:08
  • @moien at which line are you getting the error I have tested this code and it is working for me Oct 14, 2016 at 6:10
  • methodsDelegate[i] = Delegate.CreateDelegate(methods[i].DeclaringType, methods[i]);
    – moien
    Oct 14, 2016 at 6:17
  • at Line 7 methodsDelegate[i] = Delegate.CreateDelegate(methods[i].DeclaringType, methods[i]);
    – moien
    Oct 14, 2016 at 6:22
  • @moien sorry! a mistake the type you pass in a not of the Class Type but of the delegate type will update my answer shortly Oct 14, 2016 at 6:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.