Dart 2.0.0访问扩展了另一个的类的变量

时间:2018-08-09 23:44:00

标签: dart

我有这些课程(如@KevinMoore显示的here):

import 'dart:math';

class Photo {
  final double area;

  // This constructor is library-private. So no other code can extend
  // from this class.
  Photo._(this.area);

  // These factories aren't needed – but might be nice
  factory Photo.rect(double width, double height) => new RectPhoto(width, height);
  factory Photo.circle(double radius) => new CirclePhoto(radius);
}

class CirclePhoto extends Photo {
  final double radius;

  CirclePhoto(this.radius) : super._(pi * pow(radius, 2));
}

class RectPhoto extends Photo {
  final double width, height;

  RectPhoto(this.width, this.height): super._(width * height);
}

我的问题是:如果以这种方式创建Photo对象:Photo photo = new CirclePhoto(15.0, 10.0);,如何从radius对象中获得photo?我可以将radius变量设为私有,并使用getter进行获取吗?

谢谢。

2 个答案:

答案 0 :(得分:1)

您需要一个get方法:

class Rectangle {
  num left, top, width, height;

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

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

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

文档:https://www.dartlang.org/guides/language/language-tour

答案 1 :(得分:0)

您只需要将值转换为CirclePhoto即可访问radius值。 Photo没有半径,因此,如果这样做:

Photo photo = new CirclePhoto(15.0);
print(photo.radius); // Compile-time error, Photo has no "radius"

您收到一个错误,但如果您这样做:

Photo photo = new CirclePhoto(15.0);
print((photo as CirclePhoto).radius);

有效。

这会执行从PhotoCirclePhoto下播。静态类型系统无法确定这是安全的(某些照片不是圆形照片),因此它会在运行时进行检查。如果照片实际上不是CirclePhoto,则会出现运行时错误。

另一种选择是使用基于类型检查的类型提升:

Photo photo = new CirclePhoto(15.0);
if (photo is CirclePhoto) print(photo.radius);

这在photo-check保护的代码中将CirclePhoto变量提升为is。 (类型提升是相当原始的,它基本上需要是一个您没有分配给它的局部变量,并且您检查的类型必须是该变量当前类型的子类型)。

radius设为私有并添加吸气剂将使没有区别。在radius上已经有一个吸气剂名称CirclePhoto,这是您的最终字段引入的名称。将字段重命名为私有字段并添加另一个getter并没有好处,这纯粹是开销。