和有什么区别?和 !在 Map、List 和 Set 等集合中?
What's the difference between ? and ! in collections like Map, List and Set?
在 Dart 的集合中使用 ?
和 !
有什么区别?
说,我有:
var list = [1, 2];
现在,我可以使用
print(list?[0]); // prints 1
或
print(list![0]); // also prints 1
他们似乎做的是一样的工作,有什么区别?
他们两个似乎做同样的工作,因为你的 list
是 List<int>
(non-nullable) 类型而不是 List<int>?
(可为空)。如果您的列表是可为空的类型,例如:
List<int>? list;
你会看到不同。
使用?
(空感知运算符)
使用 ?
是安全的,因为如果 list
是 null
,list?[0]
仍然会打印 null
而不是抛出错误。
print(list?[0]); // Safe
或者您也可以使用 ??
来提供默认值。
print(list?[0] ?? -1); // Safe. Providing -1 as default value in case the list is null
使用 !
(Bang 运算符)
但是,!
会抛出运行时错误,因为您明确指出您的 list
不是 null
,并且您正在将它从可为 null 向下转换为 non-nullable:
print(list![0]); // Not safe. May cause runtime error if list is null
这相当于
print((list as List)[0]);
在 Dart 的集合中使用 ?
和 !
有什么区别?
说,我有:
var list = [1, 2];
现在,我可以使用
print(list?[0]); // prints 1
或
print(list![0]); // also prints 1
他们似乎做的是一样的工作,有什么区别?
他们两个似乎做同样的工作,因为你的 list
是 List<int>
(non-nullable) 类型而不是 List<int>?
(可为空)。如果您的列表是可为空的类型,例如:
List<int>? list;
你会看到不同。
使用?
(空感知运算符)
使用 ?
是安全的,因为如果 list
是 null
,list?[0]
仍然会打印 null
而不是抛出错误。
print(list?[0]); // Safe
或者您也可以使用 ??
来提供默认值。
print(list?[0] ?? -1); // Safe. Providing -1 as default value in case the list is null
使用 !
(Bang 运算符)
但是,!
会抛出运行时错误,因为您明确指出您的 list
不是 null
,并且您正在将它从可为 null 向下转换为 non-nullable:
print(list![0]); // Not safe. May cause runtime error if list is null
这相当于
print((list as List)[0]);