I’m trying to design a base abstract class that can gather all the properties from classes that are inherited from it. I’m getting the name fine, but getting the value is not working. I get the runtime error "Object does not match target". Any help is much appreciated.
public string Get()
{
string ret = "";
var type = GetType();
foreach (PropertyInfo p in this.GetType().GetProperties())
{
ret += p.Name + "`" + p.GetValue(type) + "~";
//i've also tried
//ret += p.Name + "`" + p.GetValue(this) + "~";
}
ret = ret.TrimEnd('~');
return ret;
}
>Solution :
Parameter count mismatch.
It seems that one of the properties is an indexer, you can ignore such properties by checking GetIndexParameters
on the PropertyInfo
(or process it accordingly if needed):
if (!p.GetIndexParameters().Any())
{
ret += p.Name + "`" + p.GetValue(this) + "~";
}
Demo with the runtime exception @sharplab.io.