[英]What's the difference between is! and !is in Dart?
我想看看一個變量是否不是某種類型。 我知道我可以做if(picture is XFile)
,但這些似乎都適用於相反的情況:
if(picture !is XFile)
if(picture is! XFile)
有什么不同?
x !is T
不是你想的那樣。 如果您在代碼上運行dart format
,您會看到它實際上是x! is T
x! is T
; 也就是說,它正在使用后修復!
運算符,它斷言x
不是null
,然后執行正常is T
檢查(因此產生與您預期相反的結果)。 如果靜態已知x
不可為空, dart analyze
應生成關於不必要地使用空斷言運算符的警告。
也許你的意思是比較x is! T
x is! T
和!(x is T)
。 這些表達式之間沒有邏輯差異。 有一個 linter 規則表明它is!
should be preferred ,但它沒有提供任何解釋原因。 我相信這是因為is!
表面上讀起來更好(“不是”)並且比否定括號表達式更簡單。 (然而,這種立場早於 null-safety,並且可以說is!
現在可能更令人困惑,因為存在后綴!
運算符。)
void main() {
var myNum = 5;
if (myNum is! int) {
print('myNum is an integer');
}else{
print('not an integer');
}
}
output: not an integer
,它與is !int
相同
void main() {
var myNum = null;
if (myNum is int) {
print('myNum is an integer');
}else{
print('not an integer');
}
}
output: not an integer
因為值是null
所以不是int
makes sens
void main() {
var myNum = null;
if (myNum !is int) {
print('myNum is an integer');
}else{
print('not an integer');
}
}
output: Uncaught TypeError: Cannot read properties of null (reading 'toString')Error: TypeError: Cannot read properties of null (reading 'toString')
對於編譯器它與myNum! is
myNum! is
: null安全
這就像如果myNum
是null
拋出error
並且不檢查。 如果myNum
not null
,則按is
工作。
結論:
這些似乎都適用於相反的情況:if(picture !is XFile) & if(picture is!XFile)
他們應該為相反的工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.