簡體   English   中英

is 之間有什么區別? 並且 ! 在 Dart 中?

[英]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! isnull安全

這就像如果myNumnull拋出error並且不檢查。 如果myNum not null ,則按is工作。

結論

這些似乎都適用於相反的情況:if(picture !is XFile) & if(picture is!XFile)

他們應該為相反的工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM