使用反射获取属性值时参数计数不匹配

Our*_*nas 2 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 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; //
Run Code Online (Sandbox Code Playgroud)

所以我要实例化一个通用类,并从一个字符串数组(从制表符分隔的字符串中获取)中填充它,然后我需要从该类输出List或datatable instance

dr为我的数据表填充数据行时,我dt试图从该类中获取值:

string value = property.GetValue(instance, null).ToString();
dr[property.Name.ToString()] = "";
Run Code Online (Sandbox Code Playgroud)

但在网上property.GetValue(instance).ToString();我得到以下错误:

参数计数不匹配

我到处搜索,关于此错误的其他问题不适用...

还是将类强制转换为List并返回该方法会更好?

Dan*_*nez 5

如果您要获取String(或具有索引器的任何类型)的所有属性的值,则必须有特殊情况来处理索引器。因此,如果您想获取该参数的值,则必须将值对象的数组传递给一个参数作为您想要获取的索引值。

例如,property.GetValue(test, new object [] { 0 });将在索引0处获取字符串的值。因此,如果字符串的值为“ ABC”,则结果将为'A'

最简单的事情就是跳过索引器。您可以使用来测试属性是否为索引器property.GetIndexParameters().Any()。我以为您可以在调用时使用适当的绑定标志来跳过此检查GetProperties(),但如果可以,我没有看到它。

如果要跳过代码中的索引,请更改:

PropertyInfo[] properties = target.GetProperties(); 
Run Code Online (Sandbox Code Playgroud)

至:

var properties = target.GetProperties().Where(p => !p.GetIndexParameters().Any());
Run Code Online (Sandbox Code Playgroud)