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

4

2 回答 2

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 "";
}
于 2013-03-16T08:31:43.570 回答
1

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

如果您更改ActionFunc<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 返回。

于 2013-03-16T08:36:18.767 回答