Free mag vol1 | Page 623

CHAPTER 15  TYPE REFLECTION, LATE BINDING, AND ATTRIBUTE-BASED PROGRAMMING Reflecting on Fields and Properties The implementation of ListFields() is similar. The only notable difference is the call to Type.GetFields() and the resulting FieldInfo array. Again, to keep things simple, you are printing out only the name of each field using a LINQ query. // Display field names of type. static void ListFields(Type t) { Console.WriteLine("***** Fields *****"); var fieldNames = from f in t.GetFields() select f.Name; foreach (var name in fieldNames) Console.WriteLine("->{0}", name); Console.WriteLine(); } The logic to display a type’s properties is similar as well. // Display property names of type. static void ListProps(Type t) { Console.WriteLine("***** Properties *****"); var propNames = from p in t.GetProperties() select p.Name; foreach (var name in propNames) Console.WriteLine("->{0}", name); Console.WriteLine(); } Reflecting on Implemented Interfaces Next, you will author a method named ListInterfaces() that will print out the names of any interfaces supported on the incoming type. The only point of interest here is that the call to GetInterfaces() returns an array of System.Types! This should make sense given that interfaces are, indeed, types. // Display implemented interfaces. static void ListInterfaces(Type t) { Console.WriteLine("***** Interfaces *****"); var ifaces = from i in t.GetInterfaces() select i; foreach(Type i in ifaces) Console.WriteLine("->{0}", i.Name); }  Note Be aware that a majority of the “get” methods of System.Type (GetMethods(), GetInterfaces(), etc.) have been overloaded to allow you to specify values from the BindingFlags enumeration. This provides a greater level of control on exactly what should be searched for (e.g., only static members, only public members, include private members, etc.). Consult the .NET Framework 4.5 SDK documentation for details. 565