在Dart中通过引用或指针或值传递 [英] Pass by reference or pointer or value in Dart
问题描述
我正在尝试编写一些代码,以便可以通过其他类的功能将变量加起来作为对某些作品的测试.我不想写return,extends,global变量,但仍然可以添加值.有任何想法吗?还是不可能?
I am trying to write some codes that a variable can be added up by other class's function as testing for some works. I do not want to write return, extends, global variable but still can add the value. Any Ideas? Or is it impossible?
void main() {
bbb B = new bbb();
B.bOut();
}
class bbb{
int b = 1;
void bOut(){
aaa A = aaa(this.b);
A.aAdd();
print(b);
}
}
class aaa{
int variableA;
aaa(this.variableA);
void aAdd (){
variableA++;
}
}
输出为1
推荐答案
欢迎来到SO Wesley!
Welcome to SO Wesley!
在Dart中,就像在许多其他面向对象的编程语言中一样,对象始终是按值传递的.但是您仍然可以按值传递指向对象和数组的指针.感谢@jamesdlin在评论中指出这一点.有关此主题的更多信息,请参见:是Java传递参考或值传递?
In Dart, as in many other object oriented programming languages, objects are always pass-by-value. But you can still pass pointers to objects and arrays by value. Thanks to @jamesdlin for pointing that out in the comments. For an more indepth look on this subject: Is Java pass-by-reference or pass-by-value?
除了传递 this.b
之外,您还可以简单地传递对对象的引用: bbb
并访问变量 b
.我准备了一个简单的示例:
Instead of passing this.b
you could simply pass a reference to the object: bbb
and access the variable b
. I've prepared a simple example:
输出:
0
1
代码:
class Wrapper {
int i;
}
test() {
Wrapper wrapper = Wrapper();
wrapper.i = 0;
print(wrapper.i);
increase(wrapper);
print(wrapper.i);
}
increase(Wrapper wrapper) {
wrapper.i++;
}
这篇关于在Dart中通过引用或指针或值传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!