问题
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 "";
}
I want to do smthing like this, but it gives me error:
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
What I want to do, is when something happens in GameInfoUtil.GetSource
, it will call out my delegate, and the GetFoo
method will return and not continue work.
回答1:
The Action
delegate returns void. You are trying to return the string "0".
If you change Action
to Func<string>
and return that value.
public static string GetSource(WebRequest request, Func<string> failureCallback) {
// DOING WORK HERE WITH REQUEST
if(!(WORK IS SUCCESSFULL))
{
return failureCallback();
}
return "";
}
your code will work.
The code within the lambda can't return from the outer function. Internally the lambda is converted to a regular method (with an unspeakable name).
public static string GetFoo() {
string source = GameInfoUtil.GetSource(repairRequest, () => {
return "0"; // this line gives error
});
}
is equivalent to
public static string GetFoo() {
string source = GameInfoUtil.GetSource(repairRequest, XXXYYYZZZ);
}
public static string XXXYYYZZZ()
{
return "0";
}
now you can easily understand why return "0"
can't return from GetFoo.
回答2:
An Action
delegate should return void. You cannot return a string. You can change it to 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 "";
}
来源:https://stackoverflow.com/questions/15447218/making-a-return-inside-callback