在回调内部返回 [英] Making a return inside callback
问题描述
public static string GetFoo() {
string source = GameInfoUtil.GetSource(repairRequest, () => {
return "0"; // this line gives error
});
.
.
MORE WORK, BUT WANT TO SKIP IT
}
public static string GetSource(WebRequest request, Action failureCallback) {
// DOING WORK HERE WITH REQUEST
if(WORK IS SUCCESSFULL) RETURN CORRECT STRING ELSE CALL ->
failureCallback();
return "";
}
我想做这样的东西,但它给我错误: p>
I want to do smthing like this, but it gives me error:
Error 2 Cannot convert lambda expression to delegate type 'System.Action' because some of the return types in the block are not implicitly convertible to the delegate return type.
Error 1 Since 'System.Action' returns void, a return keyword must not be followed by an object expression C:\Users\Jaanus\Documents\Visual Studio 2012\Projects\Bot\Bot\Utils\GameInfoUtil.cs 58 5 Bot
我想做什么,发生在 GameInfoUtil.GetSource
中,它将调用我的委托,并且 GetFoo
方法将返回并不继续工作。
What I want to do, is when something happens in GameInfoUtil.GetSource
, it will call out my delegate, and the GetFoo
method will return and not continue work.
推荐答案
Action
委托返回void。
The Action
delegate returns void. You are trying to return the string "0".
如果将 Action
更改为
If you change Action
to Func<string>
and return that value.
public static string GetSource(WebRequest request, Func<string> failureCallback) {
// DOING WORK HERE WITH REQUEST
if(!(WORK IS SUCCESSFULL))
{
return failureCallback();
}
return "";
}
您的代码将起作用。
lambda中的代码不能从外部函数返回。
The code within the lambda can't return from the outer function. Internally the lambda is converted to a regular method (with an unspeakable name).
public static string GetFoo() {
string source = GameInfoUtil.GetSource(repairRequest, () => {
return "0"; // this line gives error
});
}
等效于
public static string GetFoo() {
string source = GameInfoUtil.GetSource(repairRequest, XXXYYYZZZ);
}
public static string XXXYYYZZZ()
{
return "0";
}
现在你可以很容易地理解为什么返回0
无法从GetFoo返回。
now you can easily understand why return "0"
can't return from GetFoo.
这篇关于在回调内部返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!