gpt4 book ai didi

c# - 使用不带参数的 "params"关键字使用反射调用方法

转载 作者:行者123 更新时间:2023-11-30 20:57:30 25 4
gpt4 key购买 nike

就像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) 得到完全相同的结果。

最佳答案

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

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

关于c# - 使用不带参数的 "params"关键字使用反射调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16777547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com