在Dart中,我们通过构造函数简化了变量的初始化:
例如
class Foo
{
Bar _bar;
Foo(this._bar);
}
Run Code Online (Sandbox Code Playgroud)
乍一看这似乎很方便.但根据我在95%的情况下的经验,你会期望发送到构造函数的内容应该是非null的.
例如在C#中我会写:
public class Foo
{
private Bar bar;
public Foo(Bar bar)
{
if (bar == null)
throw new ArgumentNullException("bar");
this.bar = bar;
}
}
Run Code Online (Sandbox Code Playgroud)
所以我的问题是Dart中针对空参数的最佳实践是什么?鉴于我们的语言功能基本上不鼓励它?
在Dart的源代码中,他们抛出ArgumentError.
大部分时间他们不检查null变量类型.
int codeUnitAt(int index) {
if (index is !int) throw new ArgumentError(index);
// ...
Run Code Online (Sandbox Code Playgroud)
来源: dart/sdk/lib/_internal/lib/js_string.dart#L17
factory JSArray.fixed(int length) {
if ((length is !int) || (length < 0)) {
throw new ArgumentError("Length must be a non-negative integer: $length");
}
// ...
Run Code Online (Sandbox Code Playgroud)
来源: dart/sdk/lib/_internal/lib/js_array.dart#L25
Gün*_*uer -1
您可以使用断言来进行检查
assert(text != null);
Run Code Online (Sandbox Code Playgroud)
Assert 语句仅在检查模式下有效。它们在生产模式下没有影响。
所以assert对于开发来说很方便,但不影响生产中的性能。
如果您希望检查在生产中持续存在,您可以像在 C# 中那样执行
if (bar == null) {
throw new ArgumentError('Bar must not be null');
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2485 次 |
| 最近记录: |