|
Dynamic Method Invocation |
|
|
|
One very useful feature related to reflection is the ability to create object dynamically and call methods on them. You can specify which class you want a Type object, or by giving the name of an assembly and a class as string, so this makes it possible to get the name of a class from the user and create an object of the appropriate type. You can then interact with the new object just as if you’d created it with new, and use reflection to find out just you’re dealing with and what it can do. Consider the following example namespace dynref using System; public static int Main(string[] args) Type t = typeof( test ) ; } }
public class test int i ; get return prop ; } set prop = value ; } }
public test() }
public test ( int x ) i = x ; }
public int func1 ( int x ) return 2 * x ; } } } Explanation: We are using the same class here. We created a Type object
‘t’ . The Activator calss contains methods to create types of objects locally or remotely, or obtain references to existing objects. The
CreateInstance, a static method, creates a local or remote instance of an object, using the constructor that matches a specified set of arguments. The object may optionally be modified with a binder object and binding attributes. The
InvokeMember method invokes the specified member, using the specified binding constraints and matching the specified argument list. In this function we passed the name of the method which we wanted to invoke i.e
func1. Next we passed some bitmasks that specify how the search should be conducted. Default specifies that the default binding rules are used. The default binder does not follow any particular language's binding rules, rather relys on each language to provide its own binding.The method,
InvokeMethod specifies that a method is to be invoked. To use the default binder we used the null parameter. Next we passed the object on which we wanted to invoke the specified member. Then we passed met, an array containing the arguments to pass to the member to invoke. |