在回调中返回

Jaa*_*nus 1 .net c# 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 "";
    }
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

我想做的是,当 中发生某些事情时GameInfoUtil.GetSource,它将调用我的委托,并且该GetFoo方法将返回而不是继续工作。

Moh*_*han 5

委托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 "";
}
Run Code Online (Sandbox Code Playgroud)