gpt4 book ai didi

Dart - const 构造函数 : Initializing a class member using a function

转载 作者:行者123 更新时间:2023-12-03 02:48:24 25 4
gpt4 key购买 nike

我想使用相同的函数初始化几个最终成员变量。不幸的是,dart 不允许在 const 构造函数的初始化列表中调用函数:

int fun(int val) => val + 1;

class Foo {
final int a;
final int b;
final int c;
const Foo(int a, int b, int c)
: a = fun(a), <-- this won't compile because
b = fun(b), <-- the constructor
c = fun(c); <-- is const
}

我绝对需要构造函数是一个常量表达式(为了保持与现有第三方库代码的兼容性)。
我能想到的唯一解决方法是将整个函数体重复复制并粘贴到初始化列表中。
我已经在一些颤振库中看到了这种反模式。我还是宁愿避免它。
有人知道解决问题的更清洁的方法吗?

最佳答案

用私有(private)构造函数定义工厂函数怎么样?

Foo._privateConstructor(int a, int b, int c);
然后使用
factory Foo(int rawA, int rawB, int rawC) {
int a = func(rawA);
int b = func(rawB);
int c = func(rawC);
return Foo._privateConstructor(a,b,c);
}

关于Dart - const 构造函数 : Initializing a class member using a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52366880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com