繁体   English   中英

C# 从 MethodInfo 获取委托

[英]C# Get Delegate from 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;
}

Delegate.CreateDelegate委托类型最受驱动,但我为几个对象调用此方法。 如何获得委托类型?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM