16.5 Dynamically invoking methods in late bound objects


16.5 Dynamically invoking methods in late bound objects

You should have read section 16.3 before embarking on this section.

Late bound objects are objects the type of which we are unsure until runtime. Late binding is more flexible but slower to perform. We use System.Activator 's CreateInstance method to create an instance of a class during runtime.

Examine the program below:

 1: using System;  2: using System.Reflection;  3:  4: public class MyClass{  5:   public 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:     // can assign typeName to a type known during runtime 17:     string typeName = "MyClass"; 18: 19:     Type t = Type.GetType(typeName); 20:  object o  =  Activator.CreateInstance(t);  21: 22:  MethodInfo m  =  t.GetMethod("DoThis");  23:  m.Invoke(o, null);  // DoThis takes in no parameters 24:   } 25: } 

Output:

 c:\expt>test doing this 

We use MethodInfo 's Invoke method to dynamically invoke a method. Invoke is inherited from MethodBase , which is a superclass of MethodInfo .

The signature for Invoke is:

 public object Invoke (object obj, object[] parameters); 

It takes in the object instance containing the method (represented by MethodInfo ) as the first parameter, and the parameters to be passed into that method via an object array as the second parameter.

On line 23 in the example above, o and null were passed into Invoke since DoThis does not take in any parameters.

DoThat is a little bit more complex than DoThis because DoThat takes in two int s as parameters. If you want to invoke DoThat , you need to create an object array with two int s first before passing it into Invoke .

You can replace lines 20 “ 23 with the following to invoke DoThat instead:

 20:     object o = Activator.CreateInstance(t); 21:  object []param  =  {2,3};  22:     MethodInfo m = t.GetMethod("DoThat"); 23:  m.Invoke(o, param);  // DoThat takes in two parameters 

New output:

 c:\expt>test doing that 6 

Line 21 creates a new object array containing two int elements. This array is then passed into Invoke as the second parameter on line 23.



From Java to C#. A Developers Guide
From Java to C#: A Developers Guide
ISBN: 0321136225
EAN: 2147483647
Year: 2003
Pages: 221
Authors: Heng Ngee Mok

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net