不确定标题中的术语是否100%正确,但我的意思很容易通过这个例子来说明:
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中这是可能的,如果是这样,怎么样?
不,Dart不会通过引用传递参数。 (如果没有类似C ++的复杂类型系统和规则,如果调用者没有将参数绑定到变量,那么它是如何工作的还不清楚。)
您可以添加一个间接级别(即,将obj1
放在另一个对象中,例如List
,Map
或您自己的类)。另一种可能性是使doSomethingElse
成为嵌套函数,然后它可以直接访问和修改封闭范围内的变量。
你在该函数中有一个引用问题,
当你打电话给你的doSomethingElse(obj1)
时,
MyObject obj
参数引用obj1值,
那么obj
你引用了MyClass('obj1 new objcet')
,
而且你没有改变主要的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');
}