查找对象的所有属性和子属性

有时我想知道一个对象是否有我正在寻找的属性,但有时一个对象有很多属性,可能需要一些时间才能找到它进行调试。 如果我能编写一个能够在字符串中找到所有属性及其值的函数,那么我可以将该字符串粘贴到记事本中,并查找我正在寻找的值,并使用记事本具有的查找function。 到目前为止,我有这样的事情:

public void getAllPropertiesAndSubProperties(System.Reflection.PropertyInfo[] properties) { foreach (var a in properties) { //MessageBox.Show(a.ToString()); // do something here to test if property a is the one // I am looking for System.Reflection.PropertyInfo[] temp = a.GetType().GetProperties(); // if property a has properties then call the function again if (temp.Length > 0) getAllPropertiesAndSubProperties(temp); } } 

编辑我工作过的问题:

到目前为止,我添加了以下代码。 我可以将我想要的任何对象传递给以下方法,我可以看到所有属性。 我无法查看属性的值

 ![public void stackOverex(dynamic obj) { // this is the string where I am apending all properties string stringProperties = ""; Type t = obj.GetType(); List l = new List(); while (t != typeof(object)) { l.AddRange(t.GetProperties()); t = t.BaseType; var properites = t.GetType().GetProperties(); foreach (var p in properites) { string val = ""; try { val = obj.GetType().GetProperty(p.Name).GetValue(obj, null).ToString(); } catch { } stringProperties += p.Name + " - " + val + "\r\n"; } } MessageBox.Show(stringProperties); } 

在此处输入图像描述

是的Visual Studio调试器很棒,但看看对象可以拥有多少属性。 我实际上正在寻找gridViewColumnHeader的indexSomething属性我不记得我记得以前使用它的确切名称。 我有一个事件,当一个列被点击时触发,我想知道索引而不是名称“列号2?或3被点击”。 我知道我可以用它的名字来获取它,但如果我能实现这个调试器函数会很好。 看看下面的图片有多复杂。

在此处输入图像描述

如果您想要包括基本类型在内的所有属性,那么您可以这样做:

  Type t = typeof(AnyType); List l = new List(); while (t != typeof(object)) { l.AddRange(t.GetProperties()); t = t.BaseType; } 

或者你想要一个递归的属性打印,最高级别:

  public static void ReadALotOfValues(StringBuilder b, object o, int lvl, int maxLvl) { Type t = o.GetType(); List l = new List(); while (t != typeof(object)) { l.AddRange(t.GetProperties()); t = t.BaseType; } foreach (var item in l) { if (item.CanRead && item.GetIndexParameters().Length == 0) { object child = item.GetValue(o, null); b.AppendFormat("{0}{1} = {2}\n", new string(' ', 4 * lvl), item.Name, child); if (lvl < maxLvl) ReadALotOfValues(b, child, lvl + 1, maxLvl); } } } 

编辑:调用上述方法:

 object o = ...some object here...; var b = new StringBuilder(); ReadALotOfValues(b, o, 0, 5); Console.WriteLine(b.ToString()); 

以上内容将读取objeto中最多5个深度级别的属性。

必须以某种方式限制搜索,否则它将永远循环...想到一个自引用对象。