是否可以在Dart中修改参数的引用? [英] Is it possible to modify the reference of an argument in Dart?

查看:35
本文介绍了是否可以在Dart中修改参数的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不确定标题中的术语是否正确100%,但是此示例很容易说明我的意思:

Not sure if the terminology in the title is 100% correct, but what I mean is easily illustrated by this example:

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 所引用的内容,以便输出为:

But what if I wanted doSomethingElse() to actually modify what obj1 is referencing, so that the output would be:

obj1 initial
obj1 new string
obj1 new object

在Dart中有可能吗?如果可以,怎么办?

Is this possible in Dart, and if so, how?

推荐答案

否,Dart不会通过引用传递参数.(没有C ++的复杂类型系统和规则之类的东西,如果调用者未将参数绑定到变量,则不清楚如何工作.)

No, Dart does not pass arguments by reference. (Without something like C++'s complex type system and rules, it's not clear how it would work if the caller didn't bind the argument to a variable.)

您可以改为添加一个间接级别(即,将 obj1 放置在另一个对象(例如 List Map 或您自己的课程).另一种可能性是使 doSomethingElse 成为嵌套函数,然后它可以直接访问和修改封闭范围中的变量.

You instead could add a level of indirection (i.e., by putting obj1 inside another object, such as a List, Map, or your own class). Another possibility would be to make doSomethingElse a nested function, and then it could directly access and modify variables in the enclosing scope.

这篇关于是否可以在Dart中修改参数的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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