从methodinfo获取委托

Ty.*_*Ty. 33 c# reflection delegates

我有一个下拉列表,通过检查类的方法并包括与特定签名匹配的方法来填充.问题在于从列表中获取所选项目并让委托在类中调用该方法.第一种方法有效,但我无法弄清楚第二种方法的一部分.

例如,

public delegate void MyDelegate(MyState state);

public static MyDelegate GetMyDelegateFromString(string methodName)
{
    switch (methodName)
    {
        case "CallMethodOne":
            return MyFunctionsClass.CallMethodOne;
        case "CallMethodTwo":
            return MyFunctionsClass.CallMethodTwo;
        default:
            return MyFunctionsClass.CallMethodOne;
    }
}

public static MyDelegate GetMyDelegateFromStringReflection(string methodName)
{
    MyDelegate function = MyFunctionsClass.CallMethodOne;

    Type inf = typeof(MyFunctionsClass);
    foreach (var method in inf.GetMethods())
    {
        if (method.Name == methodName)
        {
            //function = method;
            //how do I get the function to call?
        }
    }

    return function;
}
Run Code Online (Sandbox Code Playgroud)

如何使第二种方法的注释部分工作?我如何MethodInfo投入代表?

谢谢!

编辑:这是工作解决方案.

public static MyDelegate GetMyDelegateFromStringReflection(string methodName)
{
    MyDelegate function = MyFunctionsClass.CallMethodOne;

    Type inf = typeof(MyFunctionsClass);
    foreach (var method in inf.GetMethods())
    {
        if (method.Name == methodName)
        {
            function = (MyDelegate)Delegate.CreateDelegate(typeof(MyDelegate), method);
        }
    }

    return function;
}
Run Code Online (Sandbox Code Playgroud)

Nat*_*ari 21

您需要调用某种形式的Delegate.CreateDelegate(),具体取决于所讨论的方法是静态方法还是实例方法.

  • 这个答案通过一个例子会更有帮助。 (7认同)

Sag*_*agi 21

private static Delegate CreateDelegate(this MethodInfo methodInfo, object target) {
    Func<Type[], Type> getType;
    var isAction = methodInfo.ReturnType.Equals((typeof(void)));
    var types = methodInfo.GetParameters().Select(p => p.ParameterType);

    if (isAction) {
        getType = Expression.GetActionType;
    }
    else {
        getType = Expression.GetFuncType;
        types = types.Concat(new[] { methodInfo.ReturnType });
    }

    if (methodInfo.IsStatic) {
        return Delegate.CreateDelegate(getType(types.ToArray()), methodInfo);
    }

    return Delegate.CreateDelegate(getType(types.ToArray()), target, methodInfo.Name);
}
Run Code Online (Sandbox Code Playgroud)

  • 这应该是公认的答案:它直接解决了问题 (2认同)
  • @Graviton取决于您是否碰巧将方法签名作为`Delegate`类型。在这种情况下,OP似乎表明他可以预先设定“ MyDelegate”,在这种情况下,Nate和OP所采用的解决方案是最好的。另一方面,这个问题是* other *问题的绝佳答案,如果您无法访问适当的`Delegate`类型(即,通常情况下,您获得的`MethodInfo`-蓝色的名称)...但是恰好需要这样的委托类型才能创建委托(一个臭名昭著的“ .NET”鸡肉和鸡蛋问题)。 (2认同)
  • 此解决方案不适用于具有 out / ref 参数类型的方法。 (2认同)