dart参数传方法_有没有办法通过引用在Dart中传递一个原始参数?

Dart语言不支持直接将基本类型按引用传递,但可以通过包装类实现类似效果。如创建一个`PrimitiveWrapper`类,将基本类型作为类的成员,然后在函数中操作这个包装类的实例来间接修改基本类型的值。此外,如果在类的方法中需要共享变量,可以考虑使用类成员代替参数传递。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I would like to pass a primitive (int, bool, ...) by reference. I found a discussion about it (paragraph "Passing value types by reference") here: value types in Dart, but I still wonder if there is a way to do it in Dart (except using an object wrapper) ? Any development ?

解决方案

The Dart language does not support this and I doubt it ever will, but the future will tell.

Primitives will be passed by value, and as already mentioned here, the only way to 'pass primitives by reference' is by wrapping them like:

class PrimitiveWrapper {

var value;

PrimitiveWrapper(this.value);

}

void alter(PrimitiveWrapper data) {

data.value++;

}

main() {

var data = new PrimitiveWrapper(5);

print(data.value); // 5

alter(data);

print(data.value); // 6

}

If you don't want to do that, then you need to find another way around your problem.

One case where I see people needing to pass by reference is that they have some sort of value they want to pass to functions in a class:

class Foo {

void doFoo() {

var i = 0;

...

doBar(i); // We want to alter i in doBar().

...

i++;

}

void doBar(i) {

i++;

}

}

In this case you could just make i a class member instead.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值