By Dragan Pesic
Did you ever need to call one function with the same name from more
than a one class , or just make an object based on a class name which
you got as an function parameter?
Well, here's how.
Let's say you've got two classes called Class1 and Class2, looking like this:
public class Class1
{
public Class1()
{
}
public int GetResult(ref string parameter1, int parameter2)
{
parameter1 = "Class1 did this";
return 1011;
}
}
public class Class2
{
public Class2()
{
}
public int GetResult(ref string parameter1, int parameter2)
{
parameter1 = "Class2 did this";
return 2048;
}
}
They don't do much, but the "trick" is to call the right one through her name,
not actually knowing which one is it.
// Replace "Remote1" with Name of the assembly where your class definitions are
string sClassName = "Remote1." + textBox1.Text;
System.Runtime.Remoting.ObjectHandle ObjHandle; // with this we "wrap" the right class
object ObjUnwrapped;
System.Reflection.MethodInfo PerformMethod;
object[] MethodParameters = new object[2]; // array of parameters
MethodParameters[0] = " "; // since it's ref string, we have to give it some value
MethodParameters[1] = 0; // integer
try
{
ObjHandle = Activator.CreateInstance("Remote1", sClassName);
ObjUnwrapped = ObjHandle.Unwrap(); // We "Unwrap the object
PerformMethod = ObjUnwrapped.GetType().GetMethod("GetResult"); // This is method we want
int Result = Convert.ToInt32(PerformMethod.Invoke( ObjUnwrapped, MethodParameters));
}
catch (Exception ex)
{
// if anything goes wrong, we end up in here
}