所以我有這個代碼應該遞歸地打印給定對象的所有屬性及其內容。迭代通過反射獲得的字典
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);
}
}
}
它不適合List
和Dictionary
工作呢,我工作的一部分Dictionary
現在。
問題是,我提取鍵和值與類型:
Type keyType = t.GetGenericArguments()[0];
Type valueType = t.GetGenericArguments()[1];
但隨後VS2013告訴我,有一個與此行的一個問題:
foreach (KeyValuePair<keyType, valueType> kvp in (Dictionary<keyType, valueType>)propValue)
它告訴我,未找到類型或名稱空間KeyType和valueType。 我錯過了什麼?
謝謝。
PS:.NET 4.5.1
'keyType'&'valueType'在你的例子是Type'但'KeyValuePair的'實例中'需要一個類型名稱,使得類型可以在運行時評估。您必須使用非泛型「Dictionary」類訪問字典並手動投射鍵和值對象。 –
Howwie
[將C#中的所有對象轉儲到日誌的最佳方式是什麼?](http:// stackoverflow。com/questions/360277 /什麼是最好的方式轉儲整個對象到一個登錄在c) –