在回调中返回
本文关键字:返回 回调 | 更新日期: 2023-09-27 18:04:06
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 "";
}
我想做这样的事情,但是它给了我错误:
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
方法会返回,而不是继续工作
Action
代表应该返回void。不能返回字符串。您可以将其更改为Func<string>
:
string source = GameInfoUtil.GetSource(repairRequest, () => {
return "0";
});
public static string GetSource(WebRequest request, Func<string> failureCallback)
{
if( <some condition> )
return failureCallback(); // return the return value of callback
return "";
}
Action
委托返回void。您正在尝试返回字符串"0"。
如果您将Action
更改为Func<string>
并返回该值
public static string GetSource(WebRequest request, Func<string> failureCallback) {
// DOING WORK HERE WITH REQUEST
if(!(WORK IS SUCCESSFULL))
{
return failureCallback();
}
return "";
}
你的代码将工作。
lambda中的代码不能从外部函数返回。在内部,lambda被转换为一个常规方法(具有一个不可说的名称)。
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";
}
现在你可以很容易地理解为什么return "0"
不能从GetFoo返回