Free mag vol1 | Page 626

CHAPTER 15  TYPE REFLECTION, LATE BINDING, AND ATTRIBUTE-BASED PROGRAMMING ->Atan2 ->Ceiling ->Ceiling ->Cos ... Reflecting on Generic Types When you call Type.GetType() in order to obtain metadata descriptions of generic types, you must make use of a special syntax involving a “back tick” character (`) followed by a numerical value that represents the number of type parameters the type supports. For example, if you wish to print out the metadata description of System.Collections.Generic.List, you would need to pass the following string into your application: System.Collections.Generic.List`1 Here, you are using the numerical value of 1, given that List has only one type parameter. However, if you wish to reflect over Dictionary, you would supply the value 2, like so: System.Collections.Generic.Dictionary`2 Reflecting on Method Parameters and Return Values So far, so good! Let’s make a minor enhancement to the current application. Specifically, you will update the ListMethods() helper function to list not only the name of a given method, but also the return type and incoming parameter types. The MethodInfo type provides the ReturnType property and GetParameters() method for these very tasks. In the following modified code, notice that you are building a string that contains the type and name of each parameter using a nested foreach loop (without the use of LINQ): static void ListMethods(Type t) { Console.WriteLine("***** Methods *****"); MethodInfo[] mi = t.GetMethods(); foreach (MethodInfo m in mi) { // Get return type. string retVal = m.ReturnType.FullName; string paramInfo = "( "; // Get params. foreach (ParameterInfo pi in m.GetParameters()) { paramInfo += string.Format("{0} {1} ", pi.ParameterType, pi.Name); } paramInfo += " )"; // Now display the basic method sig. Console.WriteLine("->{0} {1} {2}", retVal, m.Name, paramInfo); } 568 } Console.WriteLine();