c#从MethodInfo获取委托

本文关键字:获取 MethodInfo | 更新日期: 2023-09-27 18:12:57

我对这段代码有一个问题:

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委托类型大多数驱动,但我调用这个方法为几个对象。如何获取委托类型

c#从MethodInfo获取委托

这对我来说很有效。[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();
    }

使用MethodInfo.DeclaringType

Type type = methods[0].DeclaringType;

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

还可以看看MethodInfo.ReflectedType