i am trying to create a class called SurroundJob that accepts Func
but executing the incoming method is not its purpose, the task of SurroundJob is to do certain predefined things before and after calling the incoming method
however, i am having trouble getting the return value of the incoming method, so that i could pass it to the calling class :(
appended first the calling class, then the desired, but currently non-functional, 'surrounder' class and finally the exception due to the inappropriate cast attempt (TResult)method.DynamicInvoke(param)
The Calling Class
class ACoreJob
{
public void DoMyJob()
{
SurroundJob.CoreJobs<Boolean, string> coreJob = DoCoreJob;
Boolean success = false;
SurroundJob.Embed<Boolean, string>(ref success, "facebook.com", coreJob);
if (success) Trace.WriteLine("Wicked without exceptions");
}
Boolean DoCoreJob(string Target)
{
Boolean isHappy = false;
Process.Start(@"http://" + Target);
isHappy = true;
return isHappy;
}
}
The Class in Focus
class SurroundJob
{
public delegate TResult CoreJobs<TResult, T>(T param);
public static void Embed<TResult,T>(ref TResult result,T param, Delegate method)
{
if (method != null)
{
MethodInfo methodInfo = method.Method;
result = default(TResult);
try
{
Log(methodInfo.Name + " Start");
result = (TResult)method.DynamicInvoke(param);
}
catch (Exception e)
{
Troubleshoot(methodInfo.Name, e);
}
}
}
The Exception
At line: result = (TResult)method.DynamicInvoke(param);
DoCoreJob Problem: Unable to cast object of type 'ACoreJob' to type 'Boolean'.
i am new to this world and dont really know how to interact with DynamicInvoke in order to get the return value?
or is there another way to achieve my aim?
thank you sincerely!