繁体   English   中英

使用带有参数的“ params”关键字的反射调用方法

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

就像这个问题一样,我在调用带有“ 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)。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM