繁体   English   中英

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

[英]Dart 2.0.0 Access to the variable of a class that extends another

我有这些类(如@KevinMoore 在此处所示 ):

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); ,如何从photo对象获取radius 我可以将radius变量设为私有,并用吸气剂将其获取吗?

谢谢。

您需要一个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

您只需要将该值转换为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 静态类型系统无法确定这是安全的(某些照片不是圆形照片),因此它会在运行时进行检查。 如果照片实际上不是CirclePhoto ,则会出现运行时错误。

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM