C# 使用反射获取属性值时参数计数不匹配
我得到一个参数计数不匹配错误,我不明白 我有以下代码:C# 使用反射获取属性值时参数计数不匹配,c#,reflection,C#,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
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; //
因此,我要实例化一个泛型类并从字符串数组(取自制表符分隔的字符串)填充它,然后我需要从类实例
为我的datatabledt
填充datarowdr
时,我试图从类中获取值:
string value = property.GetValue(instance, null).ToString();
dr[property.Name.ToString()] = "";
但是在property.GetValue(instance.ToString()行上代码>我得到以下错误:
参数计数不匹配
我已经搜索过了,关于这个错误的其他问题不适用
或者我最好将我的类强制转换为一个列表并返回该列表?如果您试图获取字符串(或任何具有索引器的类型)的所有属性的值,那么您必须使用特殊情况来处理索引器。因此,如果您想要获取该参数的值,您必须将一个参数作为您想要获取的索引值传递给值的对象数组
例如,property.GetValue(test,新对象[]{0})
将获取索引0处的字符串值。因此,如果字符串的值为“ABC”,则结果为“A”
最简单的方法就是跳过索引器。您可以使用property.GetIndexParameters().Any()
测试属性是否是索引器。我以为您可以在调用GetProperties()
时使用适当的绑定标志跳过此检查,但如果可以,我没有看到它
如果要跳过代码中的索引,请更改:
PropertyInfo[] properties = target.GetProperties();
致:
不得不问这个问题,因为一个人不能假设,所以你用过调试器吗。。?另外,请显示此代码所在的类和/或函数的完整方法签名in@MethodMan:是的,使用调试器单步执行,当我到达那行代码时,异常被抛出。。。该类由前面的代码正确填充…setValue工作正常,但无法使用GetValueDr[property.Name.ToString()]的数据类型是什么
在这一点上看一下这里看起来像是一个类似的问题公认的答案似乎解释了如何解决问题它是一个字符串,我想将它设置为value
var properties = target.GetProperties().Where(p => !p.GetIndexParameters().Any());