使用MethodInfo创建func <t,t>

时间:2015-07-03 10:58:24

标签: c# generics reflection delegates action

我尝试使用反射来自动化方法存储库。

例如,我有一个方法。

CSV Data Set Config

我在我的命令管理员中注册了这样的内容。

public string CanCallThis(int moduleFunctionId)
{
    return "Hello";
}

这很好用,但它是一个注册每个命令的手动过程。

我尝试使用反射,以便我可以探测类的命令,然后使用反射发现的信息调用RegistrCommand方法 - 这将使生活变得更加轻松,因为我不必记住添加每个RegisterCommand条目。

我正在创建注册方法的方法,目前我的代码看起来像这样。

commandManager.RegisterCommand(moduleName,"CanCallThis", new ModuleCommand<int, string>(CanCallThis));

在上面的例子中,inputParam,returnType和unknown导致了compliation错误。我的目标是创建ModuleCommand的实例。 我确定这与创建代表有关,但我不确定如何解决这个问题。

有人可以帮我创建ModuleCommand吗?

1 个答案:

答案 0 :(得分:0)

找到解决方案,这里适合所有人。

List<MethodInfo> methodInfos = IdentifyMethods();

foreach (var methodInfo in methodInfos)
{
    ParameterInfo[] methodParams = methodInfo.GetParameters();

    if (methodParams.Length == 1)
    {
        Type returnType = methodInfo.ReturnType;
        string methodName = methodInfo.Name;
        Type inputParam = methodParams[0].ParameterType;

        Type genericFuncType = typeof(Func<,>).MakeGenericType(inputParam, returnType);
        Delegate methodDelegate = Delegate.CreateDelegate(genericFuncType, this, methodInfo);

        Type genericModuleCommandType = typeof(ModuleCommand<,>).MakeGenericType(inputParam, returnType);

        IModuleCommand o = (IModuleCommand)Activator.CreateInstance(genericModuleCommandType, methodDelegate);

        commandManager.RegisterCommand(moduleName, methodName, o);
    }
}

上面代码中的IModuleCommand是我为ModuleCommand&lt;,&gt;创建的接口。实现。这是在Registercommand方法上实现的。