Dynamically invoking methods from classes in an assembly.
using System;
using System.Reflection;
interface IMyInterface {
void PrintAString(string s);
void PrintAnInteger(int i);
void PrintSomeNumbers(string desc, int i, double d);
int GetANumber(string s);
}
public class MyClass : IMyInterface {
public MyClass() {
}
public void PrintAString(string s) {
Console.WriteLine("PrintAString: {0}", s);
}
public void PrintAnInteger(int i) {
Console.WriteLine("PrintAnInteger: {0}", i);
}
public void PrintSomeNumbers(string desc, int i, double d) {
Console.WriteLine("PrintSomeNumbers String: {0}", desc);
Console.WriteLine("Integer: {0}", i);
Console.WriteLine("Double: {0}", d);
}
public int GetANumber(string s) {
Console.WriteLine("GetANumber: {0}", s);
return 99;
}
public int DoItAll(string s, int i, double d) {
IMyInterface mi = (IMyInterface)this;
mi.PrintSomeNumbers(s, i, d);
return mi.GetANumber(s);
}
}
public class MainClass {
public static void DoDynamicInvocation(string assembly) {
Assembly a = Assembly.LoadFrom(assembly);
foreach (Type t in a.GetTypes()) {
if (t.IsClass == false)
continue;
if (t.GetInterface("IMyInterface") == null)
continue;
Console.WriteLine("Creating instance of class {0}", t.FullName);
object obj = Activator.CreateInstance(t);
object[] args = { "Dynamic", 1, 99.6 };
object result;
result = t.InvokeMember("DoItAll",BindingFlags.Default|BindingFlags.InvokeMethod,null,obj,args);
Console.WriteLine("Result of dynamic call: {0}", result);
object[] args2 = { 12 };
t.InvokeMember("PrintAnInteger",BindingFlags.Default | BindingFlags.InvokeMethod,null,obj,args2);
}
}
public static void Main(string[] args) {
MyClass dmi = new MyClass();
dmi.PrintSomeNumbers("PrintMe", 1, 1.9);
int i = dmi.GetANumber("GiveMeOne");
Console.WriteLine("I = {0}", i);
DoDynamicInvocation(args[0]);
}
}
Related examples in the same category