Dart 中输出或引用参数的等效代码

Wil*_*bin 7 dart

在 Dart 中,我如何最好地编写等效于(不可变/值/非对象)输出或引用参数的代码

例如在 C#-ish 中,我可能会编码:

function void example()
{
  int result = 0;
  if (tryFindResult(anObject, ref result))
    processResult(result);
  else
    processForNoResult();
}

function bool tryFindResult(Object obj, ref int result)
{
  if (obj.Contains("what I'm looking for"))
  {
    result = aValue;
    return true;
  }
  return false;  
}
Run Code Online (Sandbox Code Playgroud)

Cut*_*tch 5

这在 Dart 中是不可能的。Dart 邮件列表中讨论了对结构值类型、ref 或 val 关键字的支持,就像周一样。这是讨论的链接,您应该在其中表达您的愿望:

https://groups.google.com/a/dartlang.org/d/topic/misc/iP5TiJMW1F8/discussion

飞镖方式将是:

void example() {
  List result = tryFindResult(anObject);
  if (result[0]) {
    processResult(result[1]);
  } else {
    processForNoResult();
  }
}

List tryFindResult(Object obj) {
  if (obj.contains("What I'm looking for")) {
    return [true, aValue];
  }
  return [false, null];
}
Run Code Online (Sandbox Code Playgroud)

  • 另一种方法是简单地返回有问题的对象或 null 并测试是否为 null。或者省略将布尔值添加到列表中,只需添加找到的对象并测试空列表。或者使用闭包 tryFindResult(Object obj, Function callMeIfYouFindSomething) { if ... callMeIfYouFindSomething(aValue); ... (2认同)