So I have this code which is supposed to recursively print all the properties and their content of a given object.
static public void PrintProperties(object obj, int indent)
{
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);
if (property.PropertyType.Assembly == objType.Assembly && !property.PropertyType.IsEnum)
{
Console.WriteLine("{0}{1}:", indentString, property.Name);
PrintProperties(propValue, indent + 2);
}
else
{
if (null != propValue)
{
Type t = propValue.GetType();
//Console.WriteLine(":::::{0}:::::", propValue.GetType());
bool isDict = t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Dictionary<,>);
if (isDict)
{
Type keyType = t.GetGenericArguments()[0];
Type valueType = t.GetGenericArguments()[1];
foreach (KeyValuePair<keyType, valueType> kvp in (Dictionary<keyType, valueType>)propValue)
{
Console.WriteLine(string.Format("Key = {0}, Value = {1}", kvp.Key, kvp.Value));
}
}
}
Console.WriteLine("{0}{1}: {2}", indentString, property.Name, propValue);
}
}
}
It doesn't work for List
and Dictionary
yet, I'm working on the Dictionary
part right now.
Problem is, I extract the type of the key and value with:
Type keyType = t.GetGenericArguments()[0];
Type valueType = t.GetGenericArguments()[1];
But then VS2013 tells me that there is a problem with this line:
foreach (KeyValuePair<keyType, valueType> kvp in (Dictionary<keyType, valueType>)propValue)
It tells me that the type or namespace KeyType and valueType are not found. What am I missing?
Thanks.
PS : .net 4.5.1