【问题标题】:Making a return inside callback在回调中返回
【发布时间】:2013-03-16 08:30:04
【问题描述】:
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 方法将返回并且不会继续工作。

【问题讨论】:

  • 您是否有任何理由使用回调而不是正常的异常处理?这一切看起来都相当复杂——如果你对回调不完全满意,这尤其麻烦。

标签: c# .net delegates callback


【解决方案1】:

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 "";
}

【讨论】:

  • GetFoo 会返回“0”还是GetSource 会返回“0”?我需要从GetFoo返回,但从GetSource内部返回。
  • @Jaanus 不,它会在调用failureCallback(); 之后return "";。使用下一个代码if(...) return failureCallback(); else return "";
  • 我需要从GetFoo 内部调用GetFoo 的return,您的解决方案是这样做的,还是您的解决方案只使string source == "0" ?
  • @Jaanus 那是不可能的。你不能用任何编程语言来做到这一点。您永远无法从另一个函数控制函数的流程,不传递一些消息。
【解决方案2】:

Action 委托返回 void。您正在尝试返回字符串“0”。

如果您将 Action 更改为 Func&lt;string&gt; 并返回该值。

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 返回。

【讨论】:

  • return failureCallback(); 不等于 return return "0" 吗?如果 lambda 不能从外部函数返回,还有其他方法吗?
  • 相当于return (()=&gt;return "0";)();。您应该返回一个带有bool success 和string errorValue 属性的状态类,并在GetFoo 方法中检查success 属性。
  • 是的,这将是任何其他编程语言的解决方案,我认为 csharp 有一些很酷的可能性来做我需要的回调。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-26
  • 2018-08-23
  • 1970-01-01
相关资源
最近更新 更多