I'm trying to write an extension method for objects that will dump the structure of the object to the debug output. I'm running in to a problem when the propertyInfo is indexed (GetIndexParameters().Length >0).
I've tried using the following:
object value = propInfo.GetValue(myObject, propInfo.GetIndexParameteres());
this results in the following runtime error:
- Object of type 'System.Reflection.ParameterInfo' cannot be converted to type 'System.Int32'
Anyone got any ideas? The full code for the method is below:
[System.Diagnostics.Conditional("DEBUG")]
public static void DebugObject(this object debugObject)
{
System.Diagnostics.Debug.WriteLine("Debugging object: " + debugObject.GetType().Namespace);
System.Diagnostics.Debug.WriteLine(String.Format("> {0}", debugObject.GetType()));
System.Diagnostics.Debug.Indent();
try
{
if (debugObject.GetType().IsArray)
{
object[] array = ((object[])debugObject);
for (int index = 0; index < array.Length; index++)
{
System.Diagnostics.Debug.WriteLine(String.Format("- {{0}} = [{1}]", index, array[index]));
}
return;
}
object value = null;
foreach (System.Reflection.PropertyInfo propInfo in debugObject.GetType().GetProperties())
{
try
{
if (propInfo.IsIndexed())
{
System.Diagnostics.Debug.WriteLine(propInfo.ReflectedType.IsArray + " is indexed");
// THIS IS WHERE IT CHOKES. As an example, try sending in something of type System.Net.Mail.MailMessage;
value = propInfo.GetValue(debugObject, propInfo.GetIndexParameters());
}
else
{
value = propInfo.GetValue(debugObject, null);
}
if (value != null)
{
System.Diagnostics.Debug.WriteLine(String.Format("> {0} = [{1}]", propInfo.Name, value));
if (
(value.GetType() != typeof(string))
&&
(value.GetType() != typeof(int))
)
{
value.DebugObject();
}
}
}
catch (System.Reflection.TargetParameterCountException tpce)
{
System.Diagnostics.Debug.WriteLine(
String.Format(
"> Could not run GetValue for {1} (type '{0}', '{2}') because of incorrect prarmeters",
propInfo.GetType().ToString(),
propInfo.Name,
propInfo.PropertyType.Namespace
)
);
}
}
}
finally
{
System.Diagnostics.Debug.Unindent();
}
}