C# Вземете делегат от MethodInfo

Имам проблем с този код:

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 делегат тип most drived, но аз извиквам този метод за няколко обекта. Как да получите тип делегат?


person moien    schedule 14.10.2016    source източник


Отговори (2)


При мен се получи. [ 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();
    }
person moien    schedule 14.10.2016
comment
На същите редове като този: stackoverflow.com/a/16364220/1559611 - person Mrinal Kamboj; 14.10.2016

Използвайте MethodInfo.DeclaringType

Type type = methods[0].DeclaringType;

ще трябва да сте малко внимателни, ако използвате наследяване.

Разгледайте и MethodInfo.ReflectedType

person Miguel Sanchez    schedule 14.10.2016
comment
Получавам грешка и за двете -› Типът трябва да произлиза от делегат. - person moien; 14.10.2016
comment
@moien на кой ред получавате грешката. Тествах този код и той работи за мен - person Miguel Sanchez; 14.10.2016
comment
methodsDelegate[i] = Delegate.CreateDelegate(methods[i].DeclaringType, methods[i]); - person moien; 14.10.2016
comment
на ред 7 methodsDelegate[i] = Delegate.CreateDelegate(methods[i].DeclaringType, methods[i]); - person moien; 14.10.2016
comment
@moien съжалявам! грешка типът, който предавате, не е от типа на класа, а от типа на делегата, скоро ще актуализира моя отговор - person Miguel Sanchez; 14.10.2016