我正在尝试调用一个通用方法。方法定义如下:
public System.Collections.Generic.IList<T> Query<T>(string query, [string altUrl = ""])
where T : new()
这是来自 github 上的 SalesforceSharp 库。我正在尝试通过此调用创建一个额外的服务层,并且正在努力调用它。请参阅下面的代码。
public List<T> Query<T>()
{
//IList<Salesforce.Account> _returnList = null;
IList<T> _returnList = null;
Type _t = typeof(T);
SqlBuilder _sb = new SqlBuilder();
_sb.Table = _t.Name.ToString();
foreach (PropertyInfo p in _t.GetProperties()) _sb.Fields.Add(p.Name.ToString());
MethodInfo method = _Client.GetType().GetMethod("Query");
method = method.MakeGenericMethod(_t);
try
{
object[] _prms = new object[1];
_prms[0] = _sb.SQL;
_returnList = (IList<T>)method.Invoke(_Client, new object[] { _prms });
//_returnList = _Client.Query<Salesforce.Account>(_sb.SQL);
}
catch { }
return (List<T>)_returnList;
}
如果我运行它,我会在 method.invoke 行上收到一个参数计数不匹配异常,但我很困惑,因为如果我引入两个未注释的行并在没有通用调用的情况下执行,它工作正常。我已经尝试了许多包含在对象数组中的字符串数组、字符串中的字符串等的组合,但无法实现。我想也许它将第二个参数视为强制性的?但是向我的 _prms 数组添加另一个对象也没有用。
请帮忙!
谢谢, 主场
最佳答案
对于您不想为其指定值的可选参数,您必须像这样传递 Type.Missing
:
_returnList = (IList<T>)method.Invoke(_Client, new object[] { _sb.SQL, Type.Missing });
引自this reference :
Use the Missing field for invocation through reflection to obtain the default value of a parameter
另请注意,另一个问题是您当前传递的是 object[]
而不仅仅是查询字符串。
关于c# - Method.Invoke 因参数计数不匹配而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34951863/