我有这些类(如@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);
,如何从 photo
对象中获取 radius
?我可以将 radius
变量设为私有并使用getter获取它吗?
谢谢 .
2 回答
你需要
get
方法:Doc:https://www.dartlang.org/guides/language/language-tour
您只需将值转换为
CirclePhoto
即可访问radius
值 .Photo
没有半径,所以如果你这样做:你得到一个错误,但如果你这样做:
有用 .
这将执行从
Photo
到CirclePhoto
的向下转换 . 静态类型系统无法判断这是否安全(某些照片不是圆形照片),因此它会在运行时进行检查 . 如果照片实际上不是CirclePhoto
,则会出现运行时错误 .另一种选择是使用基于类型检查的类型促销:
这会将
photo
变量提升为is
-check保护的代码中的CirclePhoto
. (类型提升相当原始,它基本上需要是您未分配的局部变量,并且您检查的类型必须是当前变量类型的子类型) .使
radius
私有并添加一个getter没有任何区别 . 您已经在CirclePhoto
上有一个getter名称radius
,这是您的最终字段引入的名称 . 将字段重命名为private并添加另一个getter没有任何优势,这是纯粹的开销 .