Call a function using Reflection
Below is a code which will call a function using reflection. Note that if the function exists in an outside dll, you have to use the , separator in the className. for sure the second parameter is the name of
the function you want to invoke and the third parameter is the parameters sent to that function if exists, this parameter is of type object[].
Like i already mentioned if the function is in an external dll, send the first parameter (Class1,v.dll).
public static void CallFunctionByReflection(string className,string functionName,object[] arguments)
{
Type theType = null;
Object theObj = null;
MethodInfo DownloadInfo = null;
string [] type = className.Split(',');
try
{
if(type.Length == 1)
{
theType = Type.GetType(type[0]);
}
else
{
theType = Assembly.Load(type[1]).GetType(type[0]);
}
theObj = Activator.CreateInstance(theType);
try
{
DownloadInfo = theType.GetMethod(functionName);
if (arguments != null)
{
DownloadInfo.Invoke(theObj, arguments);
}
else
{
DownloadInfo.Invoke(theObj, null);
}
}
catch (System.Reflection.AmbiguousMatchException ame)
{
Type[] typeParams = new Type[arguments.Length];
for (int ind = 0; ind < typeParams.Length; ind++)
typeParams[ind] = typeof(System.String);
DownloadInfo = theType.GetMethod(functionName, typeParams);
DownloadInfo.Invoke(theObj, arguments);
}
}
finally
{
theType = null;
theObj = null;
DownloadInfo = null;
}
}
Don't forget to import the System.Reflection namespace.
Hope this helps,