Dynamic Invocation in C# -Using Reflection
Let us analyse.One very useful feature related to reflection is the ability to create objects dynamically and call methods on them. Class1.cs below has methods that will be dynamically invoked at runt
April 20, 2004
Let us analyse.One very useful feature related to reflection is the ability to create objects dynamically and call methods on them. Class1.cs below has methods that will be dynamically invoked at runtime from the DynamicInvoke.cs.
using System;
class Class1{
public static String method1()
{
return "I am Static method (method1) in class1";
}
public String method2()
{
return "I am a Instance Method (method2) in Class1";
}
public String method3(String s)
{
return "Hello " + s;
}
}
Save this file as Class1.cs and Compile c:/>csc /t:library Class1.cs.
using System;
using System.Reflection;
class DynamicInvoke
{
public static void Main(String [] args)
{
String path = "Class1.dll"
Assembly a = Assembly.Load(path);
//Invoking a static method
Type mm = a.GetType("Class1");
String i = (String) mm.InvokeMember ("method1",BindingFlags.Default |
BindingFlags.InvokeMethod,null,null,new object [] {}); Console.WriteLine(i);
//Invoking a non-static method
object o = Activator.CreateInstance(mm);
i = (String) mm.InvokeMember("method2",BindingFlags.Default |
BindingFlags.InvokeMethod,null,o,new object [] {});
Console.WriteLine(i);
//Invoking a non-static method with parameters
object [] par = new object[] {"Tester"};
i = (String) mm.InvokeMember("method3",BindingFlags.Default |
BindingFlags.InvokeMethod,null,o,par);
Console.WriteLine(i);
}
}
Save this file as DynamicInvoke.cs and Compile c:/>csc DynamicInvoke.cs and run C:> DynamicInvoke
Happy Coding !!!!
Read more about:
MicrosoftAbout the Author
You May Also Like