从匿名函数返回值的内联语法是什么?

What is the inline syntax for returning a value from an anonymous function?

我在 Whosebug 上查找了很多类似的帖子,但它们似乎并没有接近我的问题,因为我的 lambda 在协程中。

我的代码:

public string FetchInternetItems()
    {

      WWW www = new WWW(someURL);

      StartCoroutine(WaitForRequest(www, callback => {

      if(!string.IsNullOrEmpty(callback))
      {
        Debug.Log("Successfully worked..");
      }
      else
      {
        return "Did not connect to remote server.";
      }

      }));

摘自WaitForRequest

IEnumerator WaitForRequest(WWW www, Action<string> callback)
    {
        yield return www;

        if (string.IsNullOrEmpty(www.error))
        {
            if (callback != null)
            {
              callback(www.text);
            }
        }
        else
        {   
            Debug.Log("WWW Error: " + www.error);
        }
    }

协程 class 可以在这里找到:https://docs.unity3d.com/ScriptReference/MonoBehaviour.StartCoroutine.html

哪个 return 错误:

Anonymous function converted to a void returning delegate cannot return a value

理想情况下,我希望它 return callback,除非什么都没有通过,而是 return Did not connect to remote server. 消息。

您的 WaitForRequest-方法有一个 Action<string> 回调类型的参数。 Action 只是方法 returning nothing (void) 的委托,因此你不能在这样的情况下调用 return ...一个代表。但是,您的设计似乎无论如何都被破坏了。如果出现错误你 return 一个字符串,如果一切运行正确你想要 return WWW-instance 这看起来有点矛盾,不是吗?

如果出现错误,您可以抛出异常而不是 returning 字符串:

IEnumerator WaitForRequest(WWW www, Action<string> callback)

您现在可以这样称呼:

StartCoroutine(WaitForRequest(www, callback => 
{
    if(!string.IsNullOrEmpty(callback))
    {
        Debug.Log("Successfully worked..");
    }
    else
    {
        throw new Exception("Did not connect to remote server.");
    }
}

这里的想法是,如果您无法连接到服务器,您的应用程序就无法继续正常工作,因此您可以异常离开。

看看你的方法签名:

public string FetchInternetItems()

它希望您 return 一个字符串。

不是从方法作用域 returning 字符串,而是从匿名方法 returning 字符串。

return "Did not connect to remote server.";

上面一行表示您正在尝试 return 来自匿名方法的字符串,但不允许它导致以下错误:

Anonymous function converted to a void returning delegate cannot return a value

FetchInternetItems() 将结束其执行而不等待 coroutine WaitForRequest 完成。所以这两个执行彼此无关。话虽如此,您将无法在 FetchInternetItems().

中使用您正在 returning 的响应字符串

要解决此问题,一个简单的解决方案是将签名更改为

public void FetchInternetItems(Action<string> callBack);

这就是调用此方法的方式:

FetchInternerItems( result => { Debug.Log("This is response text from www : " + result);});

或者像这样:

FetchInternerItems(OnCompleted);


void OnCompleted(string response)
{
    Debug.Log("This is response text from www: " + response);
    // You can do other stuff here...
}

如果还有更多要了解的。请在评论部分提问。希望这有帮助。