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?
If you're trying to get the value of all properties of a String (or any type that has an indexer), then you're going to have to have a special case to deal with the indexer. So if you wanted to get the value of that parameter you'd have to pass the object array of values with one parameter as the index value you wanted to get.
For example, property.GetValue(test, new object [] { 0 });
would get the value of the string at index 0. So if the string's value was "ABC", the result of would be 'A'.
The easiest thing would be just to skip the indexer. You can test if a property is an indexer by using property.GetIndexParameters().Any()
. I thought you could skip this check by using the appropriate binding flag when calling GetProperties()
, but if you can, I didn't see it.
If you want to skip the index in your code, then change:
PropertyInfo[] properties = target.GetProperties();
To:
var properties = target.GetProperties().Where(p => !p.GetIndexParameters().Any());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With