Invoke a method using reflection with the “params” keyword without arguments

被刻印的时光 ゝ 提交于 2020-02-04 09:04:54

问题


Just like this question I'm having issues invoking a method that has the "params" keyword. I keep getting TargetParameterCountException exceptions. "Parameter count mismatch". The goal is to call this method with no parameters:

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

Here is what I have so far:

        //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[] { });

Please note that I have tried just passing null and using the overload GetMethod(string name) with exactly the same result.


回答1:


Try invoking it with a single parameter null because the C# compiler rewrites the method signature from method(params object[] parameters) to method(object[] parameters) and also the calls to that method.

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


来源:https://stackoverflow.com/questions/16777547/invoke-a-method-using-reflection-with-the-params-keyword-without-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!