c# - 从 methodinfo 获取委托(delegate)

标签 c# reflection delegates

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

例如,

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

如何让第二种方法的注释部分生效?如何将 MethodInfo 转换为委托(delegate)?

谢谢!

编辑:这是有效的解决方案。

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

最佳答案

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

关于c# - 从 methodinfo 获取委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/940675/

相关文章:

ios - 为什么我无法使用委托(delegate)将数据从 ViewController 传递到自定义 UIView? ( swift )

c# - 如何在 C# 中创建眼球追踪点的热图

c# - 如何在类构造函数参数中使用 IEnumerable<T>

c++ - 使用概念检查类型 T 是否具有字段 F

.net - 我可以使用 LINQ 表达式参数化 PropertyExpression 的属性名称吗?

c# - 使用 Reflection.Emit 创建的动态程序集崩溃,退出代码为 -532462766

c# - 处理大量文件

c# - VB.NET下的Late Binding Magic转换为C#

iphone - Objective-C 术语 : outlets & delegates

ios - 为什么这个委托(delegate)不触发是个谜