![](/img/trans.png)
[英]Invoke Class Method using Reflection with different params in constructor?
[英]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.