I have the following method which I use to iterate through all properties (just properties) in my classes and print on screen their names and values they hold, if any.
public static void PrintProperties(object obj, int indent = 1)
{
if ( obj == null )
return;
string indentString = new string (' ', indent);
Type objType = obj.GetType ();
PropertyInfo[] properties = objType.GetProperties ();
foreach ( PropertyInfo property in properties )
{
object propValue = property.GetValue (obj, null);
var elems = propValue as IList;
if ( elems != null )
{
foreach ( var item in elems )
{
PrintProperties (item, indent + 3);
}
}
else
{
if ( property.PropertyType.Assembly == objType.Assembly )
{
Console.WriteLine("{0}{1}:", indentString, property.Name);
PrintProperties (propValue, indent + 2);
}
else
{
Console.WriteLine("{0}{1}: {2}", indentString, property.Name, propValue);
}
}
}
Unfortunately, I change a property in one of my Classes from string to List<string>
to accommodate for multiple values that I had to assign there, and now I get error System.Reflection.TargetParameterCountException: 'Parameter count mismatch.'
which I don't know how to fix, and most probably is because I have a property that is List. How can i fix so that when I encounter such a property, to list all its values? Could someone help me please?
Aucun commentaire:
Enregistrer un commentaire