在Dart中能否修改参数的引用?

7

我不确定标题中的术语是否完全正确,但我的意思很容易通过以下示例说明:

class MyClass{
  String str = '';  
  MyClass(this.str);
}


void main() {
  MyClass obj1 = MyClass('obj1 initial');

  print(obj1.str);

  doSomething(obj1);  
  print(obj1.str);

  doSomethingElse(obj1);
  print(obj1.str);
}



void doSomething(MyClass obj){
  obj.str = 'obj1 new string';
}

void doSomethingElse(MyClass obj){
  obj = MyClass('obj1 new object');
}

这将会打印
obj1 initial
obj1 new string
obj1 new string

但是,如果我想让doSomethingElse()实际修改obj1所引用的内容,使输出结果为:

obj1 initial
obj1 new string
obj1 new object

这在Dart中是否可能?如果可能,怎样做呢?
2个回答

9
不,Dart不会按引用传递参数。(没有像C++这样的复杂类型系统和规则,如果调用者没有将参数绑定到变量中,它将不清楚如何工作。)
你可以通过增加间接性的方式来解决问题(例如,将obj1放入另一个对象中,比如ListMap或您自己的类)。另一种可能是将doSomethingElse作为嵌套函数,并且然后它可以直接访问和修改封闭作用域中的变量。

4

该函数存在引用问题,

当你在主函数中调用doSomethingElse(obj1)时,

MyObject obj参数引用了obj1的值

然后obj引用了MyClass('obj1新对象')

而你没有改变主函数中obj1的引用。

void doSomethingElse(MyClass obj){ // let's say we gave the parameter obj1
  // here obj referencing the obj1 value
  obj = MyClass('obj1 new object');
  //and then it is referencing the MyClass('obj1 new object') value
  //nothing change for obj1 it still referencing the same value
}

您可以像这样返回该对象并引用该对象:
class MyClass {
  String str = '';
  MyClass(this.str);
}

void main() {
  MyClass obj1 = MyClass('obj1 initial');

  print(obj1.str);

  doSomething(obj1);
  print(obj1.str);

  obj1 = doSomethingElse();
  print(obj1.str);
}

void doSomething(MyClass obj) {
  obj.str = 'obj1 new string';
}

MyClass doSomethingElse() {
  return MyClass('obj1 new object');
}

输出:在此输入图像描述


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接