如何使用反射访问精确的方法组表达式?

How to access to an exact method group expression using reflection?

我知道如何获取特定方法的 MethodInfo,也知道如何通过反射调用该方法。但是我无法弄清楚以下内容:

我有下面的赋值语句:

Func<double, double> myFunc = Math.Sqrt;

我想通过反射获得 myFunc 变量的 相同的内容,手头有 Math.Sqrt 的 MethodInfo。不幸的是,围绕 MethodInfo 构建包装器 lambda 或表达式并不令人满意。我想要这样的东西:

Func<double, double> myFunc = GetMethodGroupFor(methodInfoForMathSqrt);

如果孤立的样本没有解释我真正想做的事情,这里有更多的解释:

我必须用 100 种方法 "keys" 和委托来填充 Dictionary<string, Func<double, double>>。喜欢:

myDictionary.Add("mykey", Math.Sqrt);

但是我不想通过 100 条赋值语句来做到这一点,而是我想通过反射获得 100 条适当的 MethodInfos,然后在 for 循环中填充字典。

这可能吗?

我假设您将使用反射来查找与特定签名匹配的方法,如下所示:

IEnumerable<MethodInfo> methods = typeof(Math).GetMethods()
    .Where(method =>
    {
        if (method.ReturnType != typeof(double))
            return false;

        var parameters = method.GetParameters();
        return parameters.Length == 1 && parameters[0].ParameterType == typeof(double);
    });

从那里,您可以按如下方式填写字典:

var methodLookup = new Dictionary<string, Func<double, double>>();
foreach (MethodInfo method in methods)
{
    var name = method.DeclaringType.Name + "." + method.Name;
    var d = (Func<double, double>)Delegate.CreateDelegate(typeof(Func<double, double>), method);
    methodLookup[name] = d;
}