vendredi 21 août 2015

Parameter count mismatch when getting value of property using Reflection

I am getting a Parameter Count mismatch error which I don't understand.

I have the below code:

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; //

so I am instantiating a generic class and populating it from a string array (taken from a tab-delimited string), then I need to either output a List or a datatable from the class instance

When populating the datarow dr for my datatable dt I am trying to get the value from the class:

string value = property.GetValue(instance, null).ToString();
dr[property.Name.ToString()] = "";

but on the line property.GetValue(instance).ToString(); I get the below error:

Parameter count mismatch

I have searched around and the other questions about this error do not apply...

Or would I be better off just casting my class to a List and returning that?





Aucun commentaire:

Enregistrer un commentaire