我正在尝试创建一个名为SurroundJob的类,它接受Func
但执行传入方法不是它的目的,SurroundJob的任务是在调用传入方法之前和之后做某些预定义的事情
但是,我无法获取传入方法的返回值,因此我可以将它传递给调用类:(
首先附加调用类, 然后是期望的,但目前没有功能的“surrounder”课程 最后由于不合适的强制转换(TResult)方法导致异常.DynamicInvoke(param)
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;
}
}
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);
}
}
}
at line:result =(TResult)method.DynamicInvoke(param);
DoCoreJob问题:无法将'ACoreJob'类型的对象转换为'Boolean'类型。
我是这个世界的新手并且不知道如何与DynamicInvoke交互以获得返回值?
还是有另一种方法可以实现我的目标吗?
真诚地感谢你!
答案 0 :(得分:1)
以下是使用Func<T, TResult>
的简单示例:
void Main()
{
bool success = false;
SurroundJob.Embed(ref success, "facebook.com", DoCoreJob);
}
Boolean DoCoreJob(string Target)
{
Boolean isHappy = false;
Console.WriteLine(@"http://" + Target);
isHappy = true;
return isHappy;
}
class SurroundJob
{
public static void Embed<T, TResult>(ref TResult Result, T param, Func<T, TResult> method)
{
if(method != null)
{
try
{
Log(param.ToString());
Result = method(param);
}
catch(Exception e)
{
Troubleshoot(param.ToString(), e);
}
}
}
public static void Log(string s)
{
Console.WriteLine("Log: " + s);
}
public static void Troubleshoot(string s, Exception e)
{
Console.WriteLine("Troubleshoot: " + s);
Console.WriteLine(e.ToString());
}
}