如何使用反射调用DomainService.Load方法?

如何解决如何使用反射调用DomainService.Load方法?

| 我正在尝试构建一个实用程序方法,该方法通常将使用反射加载实体集合。这个想法是,使用该实用程序的程序员可以指定任何类型的实体,并且该方法将发现正确的EntityQuery并使用他们所请求的内容加载上下文。因此,我已经从用户那里收集了Entity类型和Where子句,现在我试图弄清楚如何调用该方法。这是我所拥有的:
public void Handle(LoadEntityQuery loadQuery,Action<LoadEntityQueryResult> reply)
{
    foreach (var entry in loadQuery.Entities)
    {

        Type entityType = entry.Key;
        Type _contextType = EmployeeJobsContext.Instance.GetType();

        MethodInfo _methodInfo = (from x in _contextType.GetMethods()
                                 where x.ReturnType.BaseType == typeof(EntityQuery)
                                 from y in x.ReturnType.GetGenericArguments()
                                 where y == entityType
                                 select x).FirstOrDefault();
        if (_methodInfo != null)
        {
            var query = _methodInfo.Invoke(EmployeeJobsContext.Instance,null);

           var _loadMethods = from x in _contextType.GetMethods()
                              where x.Name == \"Load\" &&
                                    x.GetParameters().Length == 3
                              select x;
           MethodInfo _loadMethod = null;

           if (_loadMethods != null)
           {
               foreach (MethodInfo item in _loadMethods)
               {
                   ParameterInfo[] _paramInfo = item.GetParameters();
                   if (_paramInfo[0].ParameterType.BaseType == typeof(EntityQuery) &&
                       _paramInfo[1].ParameterType.IsGenericType &&
                       _paramInfo[1].ParameterType.GetGenericArguments().Length == 1 &&
                       _paramInfo[1].ParameterType.GetGenericArguments()[0].BaseType == typeof(LoadOperation) &&
                       _paramInfo[2].ParameterType == typeof(object))
                   {
                       _loadMethod = item;
                       break;
                   }
               }
           }

           MethodInfo _loadOpMethod = this.GetType().GetMethod(\"LoadOperationResult\");
           Delegate d = Delegate.CreateDelegate(typeof(LoadOpDel),_loadOpMethod);

           if (_loadMethod != null)
           {
               object [] _params = new object[3];
               _params[0] = query;
               _params[1] = d;
               _params[2] = null;

               _loadMethod = _loadMethod.MakeGenericMethod(entityType);
               _loadMethod.Invoke(_context,_params);
           }
        }           
    }
}

public delegate void LoadOpDel(LoadOperation loadOp);

public void LoadOperationResult (LoadOperation loadOp)
{
    if (loadOp.HasError == true)
    {
        //reply(new LoadEntityQueryResult { Error = loadOp.Error.Message });
        loadOp.MarkErrorAsHandled();
    }
} 
foreach循环正在迭代Dictionary >>,其中Key是Entity类型,而值是Where子句。代码的第一部分是找到正确的EntityQuery方法并调用它以获取实际的查询。然后,它会发现正确的Load重载(我知道,可能有一种更好的方法来找到该方法:))这部分代码可以正常工作,我能够发现正确的EntityQuery和Load方法。 对于LoadOperation,我想使用LoadOperationResult作为我的委托方法。但是,当我尝试运行此代码时,收到一个异常,指出委托类型和方法类型签名不匹配。我非常确定我的签名是正确的,因为如果我直接调用Load并将函数名作为回调正常传递,则此代码将正确执行。我对反射式编程非常熟悉,但是在这一点上,将泛型和Action回调混为一谈是有点超出我的水平了。我对我做错了事茫然无知,有人对我有任何指示吗?我要走吗?谢谢你的帮助!! 杰森     

解决方法

好吧,在不了解您正在使用的类的任何其他信息的情况下,我无法真正测试我的解决方案,但是当我从for循环中删除委托创建时,我就可以使其工作。我将您的目标方法更改为静态:
public static void LoadOperationResult(LoadOperation loadOp)
并且该代表的创建没有问题。 可以说,我在这方面不是特别能干,但是我认为您只想创建一次委托,并在需要时重新使用它。为什么要一遍又一遍地创建它?     ,即使
Action<LoadOperation>
LoadOpDel
具有相同的签名,您也不​​能在它们之间进行隐式转换。在C#类型的强制中,有时这似乎不正确,但是如果您使用反射类型的强制,显然将无法发挥其魔力。     ,我发现我不需要使用反射来调用Load方法(不需要委托),而是通过基于实体类型创建通用方法直接调用Load。这是我为有兴趣的人想到的:
    /// <summary>
    /// The Action callback for the LoadEntityQuery handler. This callback is used to respond to the 
    /// LoadEntityQuery when all Load calls are complete. See the Handle method 
    /// </summary>
    private Action<LoadEntityQueryResult> _reply = null;

    /// <summary>
    /// Accumulator used to determine when the last entity has been loaded
    /// </summary>
    private int EntityCount { get; set; }

    /// <summary>
    /// Collective error container for Errors from the LoadOperation. This is value is returned via
    /// the _reply callback to the calling code.
    /// </summary>
    private List<Exception> Errors = null;

    public void Handle(LoadEntityQuery loadQuery,Action<LoadEntityQueryResult> reply)
    {
        _reply = reply;
        Errors = new List<Exception>();
        EntityCount = loadQuery.Entities.Count();

        MethodInfo _loadOpMethod = this.GetType().GetMethod(\"Load\",BindingFlags.NonPublic | BindingFlags.Instance);
        int _entityCount = loadQuery.Entities.Count();

        foreach (var entry in loadQuery.Entities)
        {
            Type entityType = entry.Key;
            Type _contextType = EmployeeJobsContext.Instance.GetType();

            MethodInfo _methodInfo = (from x in _contextType.GetMethods()
                                      where x.ReturnType.BaseType == typeof(EntityQuery)
                                      from y in x.ReturnType.GetGenericArguments()
                                      where y == entityType
                                      select x).FirstOrDefault();
            if (_methodInfo != null)
            {
                var query = _methodInfo.Invoke(EmployeeJobsContext.Instance,null);
                MethodInfo _typedLoadOpMethod = _loadOpMethod.MakeGenericMethod(new Type[] { entityType });

                _typedLoadOpMethod.Invoke(this,new[] { query,entry.Value});
            }
        }
    }

    private void Load<T>(EntityQuery<T> query,Expression<Func<T,bool>> where) where T: Entity
    {
        if (where != null)
            query = query.Where(where);

        EmployeeJobsContext.Instance.Load(query,(loadOp) =>
            {
                EntityCount--;
                if (loadOp.HasError)
                {
                    Errors.Add(loadOp.Error);
                    loadOp.MarkErrorAsHandled();
                }

                if (EntityCount == 0)
                    _reply(new LoadEntityQueryResult { ErrorList = Errors });

            },null);
    }
加载操作的处理程序监视最后一个实体完成加载,然后响应客户端加载已完成(如果发生任何错误,则为错误)。     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-