簡體   English   中英

“:”在飛鏢的類構造函數中意味着什么?

[英]What does the “:” means in class constructors in dart?

我正在閱讀關於課程的dartlang.org資源,他們注意到以下結構:

import 'dart:math';

class Point {
  final num x;
  final num y;
  final num distanceFromOrigin;

Point(x, y)
  : x = x,
    y = y,
    distanceFromOrigin = sqrt(pow(x, 2) + pow(y, 2));
}

我不太明白的是Point構造函數中的“:”以及為什么/何時應該使用它?

它啟動“初始化列表”。

如果你有像Point類中的最終字段,那么有不同的方法來初始化它們。

class Point {
  final num x = 3;
  ...
}

class Point {
  final num x;
  constructor(this.x);
}

class Point {
  final num x;
  constructor(num x) : this.x = x * 3;
}

這不行

class Point {
  final num x = 3;
  constructor(num x) {
    this.x = x * 3;
  }
}

因為無法從構造函數中修改最終字段。

初始化程序列出了一種解決此限制的方法,同時仍符合對象初始化順序的保證。 它在構造函數體之前執行。 這是一種檢查或修改(指定默認值)傳遞參數的方法,然后將它們分配給最終字段並進行一些計算。

使用this在初始化列表中只允許指定的屬性,但不能讀取它們,以防止訪問尚未初始化屬性。

對超級構造函數的調用也在初始化列表中完成,通常應該是列表中的最后一次調用。

class MyPoint extends Point {
  constructor(num x) : super(x);
}

暫無
暫無

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

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