Dart 不支持通过引用传递。 Dart 仅按值传递,就像 Java 一样。 Java 也不支持引用传递。
Java 是“按引用传递”还是“按值传递”?
https://stackoverflow.com/a/40523/1737201
下面是一个小证据。
void main() {
// The variable "myVar" is a "lvalue" (storage of value)
// Now we assign the value to "myVar" via "rvalue" "Object()"
final myVar = Object();
// Remember the old value
final oldObject = myVar;
// Now we will try to pass by reference.
// We assume that we will pass the reference of storage ("lvalue")
// ("myVar" im our case) because we cannot reference the value (pure data)
// because the value does not contain storage location information.
tryChangeMyVarByRef(myVar);
// Check the result passing by reference
// If storage of value was passed by its reference then changing
// the value in this storage should have effect.
assert(!identical(myVar, oldObject));
// Epic fail because Dart does not support pass by refernce.
print('WOW, it works!');
}
void tryChangeMyVarByRef(Object referencedStorgeOfValue) {
// Try change the value stored in referenced storage of value
referencedStorgeOfValue = Object();
}
编辑:
该值(或更正确的rvalue,表示没有任何存储的数据)不能有地址,因为该值只是一个数据。在编程中不可能引用数据(因为没有任何方法可以做到这一点),但可以引用数据的存储(例如变量的地址),因为存储总是有一些位置而不是数据(只能存储数据在某个位置但没有被引用,因为数据可以随时在这个位置被替换,因此这不能被称为对数据的引用,因为在执行数据重新分配后这可能是不正确的,但应该只被称为一些存储的引用数据)。
在编程中,术语“按引用传递”的意思是:传递值存储的引用(位置的地址)(即带有任何数据的某个变量的地址,但不传递该数据的地址)。
这允许 替换(但不仅仅是更改)存储在某个位置的数据,因为引用了存储(已知位置的地址)。
这仅意味着一件事:您传递存储某些值的变量的引用。
这并不意味着许多新手错误地认为的reference of some value(他们从未使用过 C 或 C++ 语言)。
另一个重要的事情是,在 Dart 中,对象(或实例)本身就是引用,因为它们是装箱的(值存储在堆中)。
这会产生您通过引用传递但同时您pass by value the reference 的错觉(其中作为值的引用是通过值传递的)。通过by value the reference 与通过by reference the reference 不同。
给新手的免费建议:学习 C 或 C++ 编程语言以找出以下内容之间的区别:
- 通过
by value the reference
- 通过
by reference the reference
在这两种情况下,值本身都是引用,但在第一种情况下,您按值传递值(引用),但在第二种情况下,您通过引用传递值(引用)。
享受吧!