Nic*_*CNB 3 c# generics reflection
就像这个问题一样,我在调用具有“params”关键字的方法时遇到问题。我不断收到 TargetParameterCountException 异常。“参数计数不匹配”。目标是不带参数调用此方法:
IList<T> List(params Expression<Func<T, object>>[] includeProperties);
Run Code Online (Sandbox Code Playgroud)
这是我到目前为止所拥有的:
//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[] { });
Run Code Online (Sandbox Code Playgroud)
请注意,我尝试过只传递 null 并使用重载 GetMethod(string name) 获得完全相同的结果。
尝试使用单个参数调用它,null因为 C# 编译器重写了从method(params object[] parameters)to的方法签名method(object[] parameters)以及对该方法的调用。
dynamic data = serviceInstance.GetType().GetMethod("List", new Type[] { paramsType }).Invoke(serviceInstance, new object[] { null });
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1787 次 |
| 最近记录: |