【问题标题】:Invoke a method using reflection with the "params" keyword without arguments使用不带参数的“params”关键字使用反射调用方法
【发布时间】:2013-05-27 17:00:04
【问题描述】:

就像this question 一样,我在调用具有“params”关键字的方法时遇到问题。我不断收到 TargetParameterCountException 异常。 “参数计数不匹配”。 目标是不带参数调用此方法:

IList<T> List(params Expression<Func<T, object>>[] includeProperties);

这是我目前所拥有的:

        //Get generic type
        var entityType = typeof(Applicant).Assembly.GetType(string.Format("Permet.BackEnd.ETL.Domain.Models.{0}", tableName));
        //create service that will receive the generic type
        var constructedIService = typeof(IService<>).MakeGenericType(entityType);

        //create the argument for the method that we invoke
        var paramsType = typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(entityType, typeof(object))).MakeArrayType();

        //instantiate the service using Unity (todo: fix singleton)
        var serviceInstance = UnitySingleton.Container.Resolve(constructedIService, "");

        //Invoke the service method "List" by passing it no parameters but telling it the signature to use (it has no overloads)
        //I tried without listing the params since it has no overload but same exception
        //I get exception Parameter count mismatch here
        dynamic data = serviceInstance.GetType().GetMethod("List", new Type[] { paramsType }).Invoke(serviceInstance, new object[] { });

请注意,我尝试只传递 null 并使用重载 GetMethod(string name) 得到完全相同的结果。

【问题讨论】:

  • 你做了很多工作来创建参数对象,但是你忘记了传递它。

标签: c# generics reflection


【解决方案1】:

尝试使用单个参数 null 调用它,因为 C# 编译器会将方法签名从 method(params object[] parameters) 重写为 method(object[] parameters) 以及对该方法的调用。

dynamic data = serviceInstance.GetType().GetMethod("List", new Type[] { paramsType }).Invoke(serviceInstance, new object[] { null });

【讨论】:

  • 是的,就是这样!非常感谢,不知道为什么我没有尝试过,因为我尝试了很多不同的方法! :)
猜你喜欢
  • 2016-05-26
  • 2013-04-03
  • 2012-06-16
  • 1970-01-01
  • 1970-01-01
  • 2011-01-13
  • 1970-01-01
相关资源
最近更新 更多