Free mag vol1 | Page 627

CHAPTER 15  TYPE REFLECTION, LATE BINDING, AND ATTRIBUTE-BASED PROGRAMMING If you now run this updated application, you will find that the methods of a given type are much more detailed. If you enter your good friend, System.Object, as input to the program, the following methods will display: ***** Methods ***** ->System.String ToString ( ) ->System.Boolean Equals ( System.Object obj ) ->System.Boolean Equals ( System.Object objA System.Object objB ) ->System.Boolean ReferenceEquals ( System.Object objA System.Object objB ->System.Int32 GetHashCode ( ) ->System.Type GetType ( ) ) The current implementation of ListMethods() is helpful, in that you can directly investigate each parameter and method return type using the System.Reflection object model. As an extreme shortcut, be aware that each of the XXXInfo types (MethodInfo, PropertyInfo, EventInfo, etc.) have overridden ToString() to display the signature of the item requested. Thus, you could also implement ListMethods() as follows (once again using LINQ, where you simply select all MethodInfo objects, rather than only the Name values): static void ListMethods(Type t) { Console.WriteLine("***** Methods *****"); var methodNames = from n in t.GetMethods() select n; foreach (var name in methodNames) Console.WriteLine("->{0}", name); Console.WriteLine(); } Interesting stuff, huh? Clearly the System.Reflection namespace and System.Type class allow you to reflect over many other aspects of a type beyond what MyTypeViewer is currently displaying. As you would hope, you can obtain a type’s events, get the list of any generic parameters for a given member, and glean dozens of other details. Nevertheless, at this point you have created a (somewhat capable) object browser. The major limitation, of course, is that you have no way to reflect beyond the current assembly (MyTypeViewer) or the always accessible mscorlib.dll. This begs the question, “How can I build applications that can load (and reflect over) assemblies not referenced at compile time?” G