C#从MethodInfo获取委托

时间:2016-10-14 05:48:06

标签: c# types delegates

我对此代码有疑问:

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;
}

Delegate.CreateDelegate委托类型最多,但我将此方法称为多个对象。如何获得委托类型?

2 个答案:

答案 0 :(得分:3)

它对我有用。 [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)

使用MethodInfo.DeclaringType

Type type = methods[0].DeclaringType;

如果你使用继承,你必须要小心。

另请查看MethodInfo.ReflectedType