在回调中做出回报

时间:2013-03-16 08:30:04

标签: c# .net delegates 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 "";
    }

我想做这样的事情,但它给了我错误:

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方法将返回,而不是继续工作。

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:1)

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