所以我有一个带有回调的异步 Web 请求方法:
private void DoWebRequest(string url, string titleToCheckFor,
Action<MyRequestState> callback)
{
MyRequestState result = new MyRequestState();
// ...
// a lot of logic and stuff, and eventually return either:
result.DoRedirect = false;
// or:
result.DoRedirect = true;
callback(result);
}
(只是预先指出,由于多种原因,我的 WebRequest.AllowAutoRedirect 设置为 false)
我事先不知道我可以期待多少次重定向,所以我开始:
private void MyWrapperCall(string url, string expectedTitle,
Action<MyRequestState> callback)
{
DoWebRequest(url, expectedTitle, new Action<MyRequestState>((a) =>
{
if (a.DoRedirect)
{
DoWebRequest(a.Redirect, expectedTitle, new Action<MyRequestState>((b) =>
{
if (b.DoRedirect)
{
DoWebRequest(b.Redirect, expectedTitle, callback);
}
}));
}
}));
}
现在我脑子崩溃了,我怎么能把它放在一个迭代循环中,这样如果不再需要重定向,它就会最后回调回原始调用者?
最佳答案
存储对递归方法的引用,以便它可以调用自身:
private void MyWrapperCall(string url, string expectedTitle, Action<MyRequestState> callback)
{
Action<MyRequestState> redirectCallback = null;
redirectCallback = new Action<MyRequestState>((state) =>
{
if(state.DoRedirect)
{
DoWebRequest(state.Redirect, expectedTitle, redirectCallback);
}
else
{
callback(state);
}
});
DoWebRequest(url, expectedTitle, redirectCallback);
}
关于c# - 如何实现递归回调模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10351965/