I am currently doing a recursive to get all the fields in a given class. A class can have normal fields (string, int, ect..) or class type field like (Class2, Class3) and even Lists of normal types or class types.
My current code is
private void ShowFields(object obj, TreeNodeCollection nodes)
{
try
{
foreach (FieldInfo fi in obj.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance))
{
nodes.Add(fi.Name + " = " + fi.GetValue(obj));
object val = fi.GetValue(obj);
if (val.ToString().Contains("System.Collections."))
{
IList list = fi.GetValue(obj) as IList;
for (int i = 0; i < list.Count; i++)
ShowFields(list[i], nodes[nodes.Count - 1].Nodes.Add("Item " + i + " = " + list[i]).Nodes);
}
else
ShowFields(fi.GetValue(obj), nodes[nodes.Count - 1].Nodes);
}
}
catch { }
}
But this code gives an OutOfMemoryException because it loops into the normal types too and it doesn't end until the exception is thrown..
Is there any solution to this ? Thanks in advance !
Aucun commentaire:
Enregistrer un commentaire