16.3. Retrieving methods from a type

You can retrieve a single MethodInfo object, if you already know the name of the method, or an array of MethodInfo objects.

In the following example, MyClass contains a method called DoThis() which takes in no parameters. Some useful methods of MethodInfo are demonstrated.

 1: using System;
 2: using System.Reflection;
 3:
 4: public class MyClass{
 5:   public static void DoThis(){
 6:     Console.WriteLine("doing this");
 7:   }
 8:   public static void DoThat(){
 9:     Console.WriteLine("doing that");
10:   }
11: }
12:
13: public class TestClass{
14:   public static void Main(){
15:
16:     Type t = Type.GetType("MyClass");
17:     MethodInfo m = t.GetMethod("DoThis");
18:     Console.WriteLine("method       :" + m);
19:     Console.WriteLine("Name         :" + m.Name);
20:     Console.WriteLine("IsPublic     :" + m.IsPublic);
21:     Console.WriteLine("IsStatic     :" + m.IsStatic);
22:     Console.WriteLine("IsConstructor:" + m.IsConstructor);
23:     Console.WriteLine("ReturnType   :" + m.ReturnType);
24:   }
25: }

Output:

c:expt>test
method       :Void DoThis()
Name         :DoThis
IsPublic     :True
IsStatic     :True
IsConstructor:False
ReturnType   :System.Void

If you don't know the method name in the type, you can obtain an array of all MethodInfo objects in a particular type:

 1: using System;
 2: using System.Reflection;
 3:
 4: public class MyClass{
 5:   public static void DoThis(){
 6:     Console.WriteLine("doing this");
 7:   }
 8:   public void DoThat(int a, int b){
 9:     Console.WriteLine("doing that " + (a*b));
10:   }
11: }
12:
13: public class TestClass{
14:   public static void Main(){
15:
16:     Type t = Type.GetType("MyClass");
17:     MethodInfo[] methods = t.GetMethods();
18:
19:     foreach (MethodInfo m in methods)
20:       Console.WriteLine("method: " + m);
21:   }
22: }

Output:

c:expt>test
method: Int32 GetHashCode()
method: Boolean Equals(System.Object)
method: System.String ToString()
method: Void DoThis()
method: Void DoThat(Int32, Int32)
method: System.Type GetType()

Notice that several methods such as GetHashCode, Equals, and ToString inherited from System.Object to MyClass are also retrieved.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.240.252