How to perform dynamic object creation and method invocation in .NET 3.5

What does the code that would create the class object look like:

string myClass = "MyClass"; 

From the above type, then call

 string myMethod = "MyMethod"; 

At this facility?

+2
source share
4 answers

Example, but without error checking:

 using System; using System.Reflection; namespace Foo { class Test { static void Main() { Type type = Type.GetType("Foo.MyClass"); object instance = Activator.CreateInstance(type); MethodInfo method = type.GetMethod("MyMethod"); method.Invoke(instance, null); } } class MyClass { public void MyMethod() { Console.WriteLine("In MyClass.MyMethod"); } } } 

Each step requires careful verification - you cannot find the type, it may not have a constructor without parameters, you cannot find this method, you can call it with the wrong argument types.

One note: Type.GetType (string) needs the name assigned to the assembly if it is not running in the current executable assembly or mscorlib.

+10
source

I created a library that simplifies the creation and invocation of dynamic objects using .NET. You can download the library and code in google code: Late Binding Helper In the project, you will find the Wiki page using , or you can also check this article in CodeProject

Using my library, your example will look like this:

 IOperationInvoker myClass = BindingFactory.CreateObjectBinding("MyClassAssembly", "MyClass"); myClass.Method("MyMethod").Invoke(); 

Or even shorter:

 BindingFactory.CreateObjectBinding("MyClassAssembly", "MyClass") .Method("MyMethod") .Invoke(); 

It uses a free interface and really simplifies such operations. Hope you could find this helpful.

+3
source

The following assumes an object with an open constructor and a public method that returns some value but does not accept any parameters.

 var object = Activator.CreateInstance( "MyClass" ); var result = object.GetType().GetMethod( "MyMethod" ).Invoke( object, null ); 
+2
source

Assuming your class is in your runtime assembly, your constructor and your method are without parameters.

 Type clazz = System.Reflection.Assembly.GetExecutingAssembly().GetType("MyClass"); System.Reflection.ConstructorInfo ci = clazz.GetConstructor(new Type[] { }); object instance = ci.Invoke(null); /* Send parameters instead of null here */ System.Reflection.MethodInfo mi = clazz.GetMethod("MyMethod"); mi.Invoke(instance, null); /* Send parameters instead of null here */ 
0
source

All Articles