有没有办法在 Dart 中通过引用传递原始参数? [英] Is there a way to pass a primitive parameter by reference in Dart?

查看:30
本文介绍了有没有办法在 Dart 中通过引用传递原始参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过引用传递一个原语 (int, bool, ...).我在这里找到了关于它的讨论(段落通过引用传递值类型"):Dart 中的值类型,但我仍然想知道是否有办法在 Dart 中做到这一点(除了使用对象包装器)?有什么发展吗?

I would like to pass a primitive (int, bool, ...) by reference. I found a discussion about it (paragraph "Passing value types by reference") here: value types in Dart, but I still wonder if there is a way to do it in Dart (except using an object wrapper) ? Any development ?

推荐答案

Dart 语言不支持这一点,我怀疑它永远不会,但未来会告诉我们.

The Dart language does not support this and I doubt it ever will, but the future will tell.

原语将按值传递,正如这里已经提到的,通过引用传递原语"的唯一方法是将它们像这样包装:

Primitives will be passed by value, and as already mentioned here, the only way to 'pass primitives by reference' is by wrapping them like:

class PrimitiveWrapper {
  var value;
  PrimitiveWrapper(this.value);
}

void alter(PrimitiveWrapper data) {
  data.value++;
}

main() {
  var data = new PrimitiveWrapper(5);
  print(data.value); // 5
  alter(data);
  print(data.value); // 6
}

如果您不想这样做,那么您需要找到解决问题的另一种方法.

If you don't want to do that, then you need to find another way around your problem.

我看到人们需要通过引用传递的一种情况是,他们想要传递给类中的函数的某种值:

One case where I see people needing to pass by reference is that they have some sort of value they want to pass to functions in a class:

class Foo {
  void doFoo() {
    var i = 0;
    ...
    doBar(i); // We want to alter i in doBar().
    ...
    i++;
  }

  void doBar(i) {
    i++;
  }
}

在这种情况下,您可以将 i 设为类成员.

In this case you could just make i a class member instead.

这篇关于有没有办法在 Dart 中通过引用传递原始参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆