将一个随机值传递给两个超级参数
Passing one random value to two super arguments
基本上我想将一个随机参数传递给 parent class 两次。
考虑以下示例:
import 'dart:math' as math;
class A {
double a;
double b;
A(this.a, this.b) {
if (a != b) {
print('Error');
} else {
print('Alright');
}
}
}
class B extends A {
B() : super(math.Random().nextDouble(), math.Random().nextDouble());
}
main() {
B();
}
这是我能想出的唯一解决方案,但这感觉太老套了...我希望其他人能为我提供更好的解决方案。
import 'dart:math' as math;
class A {
double a;
double b;
A(this.a, this.b) {
if (a != b) {
print('Error');
} else {
print('Alright');
}
}
}
class B extends A {
static List<double> _c = [0];
bool uselessBool;
B() : uselessBool = random(),
super(_c[0], _c[0]);
static bool random() {
_c[0] = math.Random().nextDouble();
return true;
}
}
main() {
B();
}
我可能存在的东西是这样的(就像你在 python 中所做的那样):
import 'dart:math' as math;
class A {
double a;
double b;
A(this.a, this.b) {
if (a != b) {
print('Error');
} else {
print('Alright');
}
}
}
class B extends A {
B() {
var c = math.Random().nextDouble();
super(c, c);
}
}
main() {
B();
}
您可以通过创建以 _
开头的命名构造函数来创建隐藏构造函数。通过这样做,我们可以创建以下示例来执行您想要的操作:
import 'dart:math' as math;
class A {
double a;
double b;
A(this.a, this.b) {
if (a != b) {
print('Error');
} else {
print('Alright');
}
}
}
class B extends A {
B() : this._(math.Random().nextDouble());
B._(double value) : super(value, value);
}
void main() {
B();
}
如果您想要更复杂的逻辑,您还可以查看工厂构造函数,它基本上用作静态方法,但必须 return class.
的实例
基本上我想将一个随机参数传递给 parent class 两次。
考虑以下示例:
import 'dart:math' as math;
class A {
double a;
double b;
A(this.a, this.b) {
if (a != b) {
print('Error');
} else {
print('Alright');
}
}
}
class B extends A {
B() : super(math.Random().nextDouble(), math.Random().nextDouble());
}
main() {
B();
}
这是我能想出的唯一解决方案,但这感觉太老套了...我希望其他人能为我提供更好的解决方案。
import 'dart:math' as math;
class A {
double a;
double b;
A(this.a, this.b) {
if (a != b) {
print('Error');
} else {
print('Alright');
}
}
}
class B extends A {
static List<double> _c = [0];
bool uselessBool;
B() : uselessBool = random(),
super(_c[0], _c[0]);
static bool random() {
_c[0] = math.Random().nextDouble();
return true;
}
}
main() {
B();
}
我可能存在的东西是这样的(就像你在 python 中所做的那样):
import 'dart:math' as math;
class A {
double a;
double b;
A(this.a, this.b) {
if (a != b) {
print('Error');
} else {
print('Alright');
}
}
}
class B extends A {
B() {
var c = math.Random().nextDouble();
super(c, c);
}
}
main() {
B();
}
您可以通过创建以 _
开头的命名构造函数来创建隐藏构造函数。通过这样做,我们可以创建以下示例来执行您想要的操作:
import 'dart:math' as math;
class A {
double a;
double b;
A(this.a, this.b) {
if (a != b) {
print('Error');
} else {
print('Alright');
}
}
}
class B extends A {
B() : this._(math.Random().nextDouble());
B._(double value) : super(value, value);
}
void main() {
B();
}
如果您想要更复杂的逻辑,您还可以查看工厂构造函数,它基本上用作静态方法,但必须 return class.
的实例