跳至主要內容

方法

方法是為物件提供行為的函式。

例項方法

#

物件上的例項方法可以訪問例項變數和 this。以下示例中的 distanceTo() 方法是例項方法的一個例子

dart
import 'dart:math';

class Point {
  final double x;
  final double y;

  // Sets the x and y instance variables
  // before the constructor body runs.
  Point(this.x, this.y);

  double distanceTo(Point other) {
    var dx = x - other.x;
    var dy = y - other.y;
    return sqrt(dx * dx + dy * dy);
  }

}

運算子

#

大多數運算子是具有特殊名稱的例項方法。Dart 允許您定義以下名稱的運算子

<><=>===~
-+/~/*%
|ˆ&<<>>>>>
[]=[]

要宣告一個運算子,請使用內建識別符號 operator,然後是您要定義的運算子。以下示例定義了向量加法 (+)、減法 (-) 和相等性 (==)

dart
class Vector {
  final int x, y;

  Vector(this.x, this.y);

  Vector operator +(Vector v) => Vector(x + v.x, y + v.y);
  Vector operator -(Vector v) => Vector(x - v.x, y - v.y);

  @override
  bool operator ==(Object other) =>
      other is Vector && x == other.x && y == other.y;

  @override
  int get hashCode => Object.hash(x, y);
}

void main() {
  final v = Vector(2, 3);
  final w = Vector(2, 2);

  assert(v + w == Vector(4, 5));
  assert(v - w == Vector(0, 1));
}

Getter 與 Setter

#

Getter 和 Setter 是特殊方法,它們提供對物件屬性的讀寫訪問。回想一下,每個例項變數都有一個隱式 Getter,如果合適,還有一個 Setter。您可以使用 getset 關鍵字實現 Getter 和 Setter 來建立額外的屬性

dart
class Rectangle {
  double left, top, width, height;

  Rectangle(this.left, this.top, this.width, this.height);

  // Define two calculated properties: right and bottom.
  double get right => left + width;
  set right(double value) => left = value - width;
  double get bottom => top + height;
  set bottom(double value) => top = value - height;
}

void main() {
  var rect = Rectangle(3, 4, 20, 15);
  assert(rect.left == 3);
  rect.right = 12;
  assert(rect.left == -8);
}

使用 Getter 和 Setter,您可以從例項變數開始,稍後用方法封裝它們,而無需更改客戶端程式碼。

抽象方法

#

例項、Getter 和 Setter 方法可以是抽象的,它們定義了一個介面,但將其實現留給其他類。抽象方法只能存在於抽象類混入中。

要使一個方法成為抽象方法,請使用分號 (;) 代替方法體

dart
abstract class Doer {
  // Define instance variables and methods...

  void doSomething(); // Define an abstract method.
}

class EffectiveDoer extends Doer {
  void doSomething() {
    // Provide an implementation, so the method is not abstract here...
  }
}