在 Dart 1.0.0 上,我刚刚尝试过:
class MyClass {
int x;
bool b;
MyClass(int x, [bool b = true]) {
if(?b) {
// ...
}
}
}
并且在
?b
上遇到编译器错误部分:The argument definition test ('?' operator) has been deprecated
那么测试是否提供参数的"new"方法是什么?
最佳答案
没有办法测试是否提供了参数。删除它的主要原因是,以这种方式转发调用非常复杂。
通常首选的方法是使用 null
如“未给予”。这并不总是有效(例如,如果 null
是有效值),并且不会捕获错误的参数。如 null
使用,则参数不能有默认值。否则参数不为空而是采用默认值:
foo([x = true, y]) => print("$x, $y");
foo(); // prints "true, null"
因此,在您的情况下,您可能应该这样做:
class MyClass {
int x;
bool b;
MyClass(int x, [bool b]) {
if(b == null) { // treat as if not given.
// ...
}
}
}
这使得
new MyClass(5, null)
和 new MyClass(5)
完全相同的。如果你真的需要捕获第一种情况,你必须解决类型系统:class _Sentinel { const _Sentinel(); }
...
MyClass(int x, [b = const _Sentinel()]) {
if (b == const _Sentinel()) b = true;
...
}
通过这种方式,您可以检查是否提供了参数。作为返回,您会丢失
b
上的类型.
关于Dart 参数定义测试已弃用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20864811/