Anggaplah kita mempunya sebuah class Person seperti ini.
public class Person { public Person() { Childs = new List(); } public string Name { get; set; } public int Age { get; set; } public Address PostalAddress { get; set; } public Person Parent { get; set; } public List Childs { get; set; } } public class Address { public string Street { get; set; } }
Kita ingin mencetak seluruh property yang tidak null dari object Person di atas termasuk object dan collection yang ada di dalamnya menggunakan reflection.
private static 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); var elems = propValue as IList; if (elems != null) { if (elems.Count > 0) { Console.WriteLine("{0}{1}:", indentString, property.Name); foreach (var item in elems) { PrintProperties(item, indent + 3); } } }else { if (property.PropertyType.Assembly == objType.Assembly) { if (propValue != null) { Console.WriteLine("{0}{1}:", indentString, property.Name); PrintProperties(propValue, indent + 2); } }else { Console.WriteLine("{0}{1}: {2}", indentString, property.Name, propValue); } } } }
var child1 = new Person() { Name = "Abe", Age = 1 }; var child2 = new Person() { Name = "Lisa", Age = 5 }; var parent = new Person() { Name = "Me", Age = 40, PostalAddress = new Address { Street = "Bandung Soekarno Hatta" } }; parent.Childs.Add(child1); parent.Childs.Add(child2); PrintProperties(parent, 1);
Ketika dijalankan, hasilnya seperti ini: