![](/img/trans.png)
[英]Getting Unhandled Exception: System.Reflection.TargetParameterCountException: Parameter count mismatch
[英]Parameter count mismatch when getting value of property using Reflection
我收到了我不理解的参数计数不匹配错误。
我有以下代码:
Type target = Type.GetType("CPS_Service." + DocumentType);
// Create an instance of my target class
instance = Activator.CreateInstance(target);
foreach (XElement pQ in PQData.Elements())
{
try
{
// populate the member in the instance of the data class with the value from the MQ String
if (target.GetProperty(pQ.Attribute("name").Value) != null)
{
target.GetProperty(pQ.Attribute("name").Value).SetValue(instance, pqRequest[Convert.ToInt32(pQ.Attribute("pos").Value)], null);
}
}
}
PropertyInfo[] properties = target.GetProperties();
foreach (PropertyInfo property in properties)
{
DataColumn col = new DataColumn(property.Name);
col.DataType = System.Type.GetType("System.String");
col.DefaultValue = "";
dt.Columns.Add(col);
}
DataRow dr = dt.NewRow();
foreach (PropertyInfo property in properties)
{
string value = property.GetValue(instance).ToString();
dr[property.Name.ToString()] = "";
}
dt.Rows.Add(dr);
return dt; //
所以我要实例化一个通用类,并从一个字符串数组(从制表符分隔的字符串中获取)中填充它,然后我需要从类instance
输出List或datatable
当为我的数据表dt
填充datarow dr
,我试图从该类中获取值:
string value = property.GetValue(instance, null).ToString();
dr[property.Name.ToString()] = "";
但是就行property.GetValue(instance).ToString();
我收到以下错误:
参数计数不匹配
我到处搜索,关于此错误的其他问题不适用...
还是将类强制转换为List并返回该方法会更好?
如果您试图获取String(或具有索引器的任何类型)的所有属性的值,则必须有特殊情况来处理索引器。 因此,如果要获取该参数的值,则必须将值对象的数组传递给一个要获取的索引值。
例如, property.GetValue(test, new object [] { 0 });
将在索引0处获得字符串的值。因此,如果字符串的值为“ ABC” ,则结果为'A' 。
最简单的事情就是跳过索引器。 您可以使用property.GetIndexParameters().Any()
来测试属性是否为索引器。 我以为您可以在调用GetProperties()
时通过使用适当的绑定标志来跳过此检查,但是如果可以,我没有看到它。
如果要跳过代码中的索引,请更改:
PropertyInfo[] properties = target.GetProperties();
至:
var properties = target.GetProperties().Where(p => !p.GetIndexParameters().Any());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.