【问题标题】:Create func<T,T> using MethodInfo使用 MethodInfo 创建 func<T,T>
【发布时间】:2015-07-03 10:58:23
【问题描述】:

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

例如我有一个方法。

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

我是这样在我的命令管理器中注册的。

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

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

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

我正在创建注册方法的方法,目前我的代码如下所示。

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;

        commandManager.RegisterCommand(moduleName, methodInfo.Name, new ModuleCommand<inputParam, returnType>(unknown));
    }
}

在上述示例中,inputParam、returnType 和 unknown 会导致编译错误。我的目标是创建一个 ModuleCommand 实例。 我确定这与创建委托有关,但我不知道该怎么做。

有人可以帮我创建 ModuleCommand 吗?

【问题讨论】:

  • 我猜你的编译器错误之一来自:methodParams.Length = 1
  • 我想知道如果您注册并使用反射调用它们,为什么会有通用代表?在这种情况下,您不需要编译时类型。它使事情变得更加复杂。直接注册MethodInfo怎么样?
  • Type genericType = typeof (ModuleCommand).MakeGenericType(inputParam, returnType); IModuleCommand o = (IModuleCommand)Activator.CreateInstance(genericType, null);让我更近了一步,但现在我在调用 Activator.CreateInstance 时遇到问题,因为这需要将参数传递给构造函数,参数就是方法本身。

标签: c# generics reflection delegates action


【解决方案1】:

找到了解决办法,给大家。

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 实现的接口。这就是在 Registercommand 方法上实现的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多