2013-03-16 44 views
0
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 ""; 
    } 

我想做的事情smthing這樣的,但它給我的錯誤:使內回調返回

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

是否有任何理由使用回調而不是普通的異常處理?這一切似乎都相當複雜 - 如果您對回調不太滿意,這尤其麻煩。 – 2013-03-16 08:50:36

回答

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。

+0

does not'return failureCallback();'等於'return return「0」'?如果lambda不能從外部函數返回,有沒有辦法做到這一點呢? – Jaanus 2013-03-16 08:44:50

+0

它相當於'return(()=> return「0」;)();'。您應該使用'bool success'和'string errorValue'屬性返回一個狀態類並檢查GetFoo方法中的'success'屬性。 – 2013-03-16 08:47:29

+0

對於任何其他編程語言來說,這是一個解決方案,我認爲csharp有一些很酷的可能性來做我需要的回調。 – Jaanus 2013-03-16 08:48:53

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

那麼'GetFoo'會返回「0」,還是'GetSource'會返回「0」?我需要從'GetFoo'返回,但是從'GetSource'內部返回。 – Jaanus 2013-03-16 08:34:47

+0

@Jaanus不會,它會'返回'「;'調用'failureCallback();'後。使用下一個代碼'if(...)return failureCallback();否則返回「」;' – 2013-03-16 08:36:02

+0

@Jaanus我改變了代碼以匹配你所需要的。 – 2013-03-16 08:39:41