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

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

问题描述

我想通过引用传递一个原始(int,bool,...)。我在这里找到了一个讨论(通过引用传递值类型):值类型在Dart ,但我仍然想知道是否有一种方法在Dart(除非使用对象包装器)。任何开发?

解决方案

Dart语言不支持这个,我怀疑它会,但未来会告诉。 p>

基元将按值传递,如前所述,通过引用传递基元的唯一方法是将它们包装为:

  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
}

如果你不想这样做,找到另一种方式解决你的问题。



我看到人们需要通过引用传递的一个情况是,他们有一些值他们想传递给函数在class:

  class Foo {
void doFoo(){
var i = 0;
...
doBar(i); //我们想在doBar()中改变i。
...
i ++;
}

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

在这种情况下, c> i 代替类成员。


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 ?

解决方案

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

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

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

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