Dart 笔记 10 - 类(3)

特殊类

枚举

enum Color { red, green, blue }

枚举中的每个值都有一个 index 属性,并且提供 getter 方法,它返回声明时值的索引,从 0 开始。

assert(Color.red.index == 0);
assert(Color.green.index == 1);
assert(Color.blue.index == 2);

values 属性获取所有值的列表

List<Color> colors = Color.values;
assert(colors[2] == Color.blue);

可以在 switch 语句中使用 enum,如果 switch 的 case 不处理 enum 的所有值,将会报一个警告消息:

var aColor = Color.blue;

switch (aColor) {
  case Color.red:
    print('Red as roses!');
    break;
  case Color.green:
    print('Green as grass!');
    break;
  default: // Without this, you see a WARNING.
    print(aColor); // 'Color.blue'
}

可调用的类

实现 call() 方法可以让类像函数一样被调用。

WannabeFunction 类定义了一个 call() 函数,该函数接受三个字符串并将它们连接起来,每个字符串用空格分隔,并在结尾加一个感叹号。

class WannabeFunction {
  call(String a, String b, String c) => '$a $b $c!';
}

main() {
  var wf = WannabeFunction();
  // 像函数一直执行,其实就是省略了 .call
  var out = wf("Hi", "there,", "gang");
  print('$out'); // Hi there, gang!
}

静态

静态变量和方法整个文件内可见。一般优先使用顶级函数。

import 'dart:math';

class Queue {
  static const initialCapacity = 16;
}

class Point {
  num x, y;
  Point(this.x, this.y);

  static num distanceBetween(Point a, Point b) {
    var dx = a.x - b.x;
    var dy = a.y - b.y;
    return sqrt(dx * dx + dy * dy);
  }
}

void main() {
  assert(Queue.initialCapacity == 16);

  var a = Point(2, 2);
  var b = Point(4, 4);
  var distance = Point.distanceBetween(a, b);
  assert(2.8 < distance && distance < 2.9);
  print(distance);
}

比较对象

实现 Comparable 接口,以指示一个对象可以与另一个对象进行比较,通常用于排序。compareTo() 方法返回值表示大小关系:<0 表示更小,=0 表示相等,>0 表示更大。

class Line implements Comparable<Line> {
  final int length;
  const Line(this.length);

  @override
  int compareTo(Line other) => length - other.length;
}

void main() {
  var short = const Line(1);
  var long = const Line(100);
  assert(short.compareTo(long) < 0);
}

猜你喜欢

转载自blog.csdn.net/weixin_34358365/article/details/87217029