Method information centers on the MethodInfo class. You can obtain an instance of this through the GetMethod or GetMethods methods on the Type object, as shown in the following example: Type t = cust.GetType(); MethodInfo method = t.GetMethod("DoSomething"); Before diving into a code example, let's take a look at Table 11.2, which lists some of the common properties and methods available for the MethodInfo class.
Now let's see some of these methods and properties in action, as shown in the sample code in Listing 11.1. Listing 11.1. Reflecting on Methods and Parameters
The output of the preceding code looks as follows: DoSomething -------------------------- Abstract: False, Visible to Assembly: False, Constructor: False, Sealed: False Generic: True, Virtual: False, Static: False DoSomething returns System.String Parameters: input : U [In]* Generic otherCustomer : ReflectMethods.Customer`1[System.String]& [In] newCustomer : ReflectMethods.Customer`1[System.String]& [Out] anotherInput : System.Int32 [In] Local variables within method: System.Int32 (0) System.String (1) System.String (2) The Customer class on which the preceding code is reflecting is shown here: using System; using System.Collections.Generic; using System.Text; namespace ReflectMethods { class Customer<T> { private int privData = 12; public int PubData { get { return privData; } set { privData = value; } } public string DoSomething<U>(U input, ref Customer<T> otherCustomer, out Customer<T> newCustomer, int anotherInput) { int z = 21; string localString = "local"; newCustomer = new Customer<T>(); return input.ToString(); } } } One thing that might be somewhat surprising for developers who have prior experience with reflection is that generics are completely compatible with reflection. Using reflection, you can obtain all information about a method, even information related to generic type parameters. Also, if you look back at the otherCustomer and newCustomer parameters in the console output, you can see that those parameters aren't indicated as being generic. In fact, you can see that as far as the runtime is concerned, those parameters are of type Customer<string>. |