首页 文章

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

提问于
浏览
0

我有这些类(如@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 回答

  • 0

    你需要 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);
    }
    

    Doc:https://www.dartlang.org/guides/language/language-tour

  • 1

    您只需将值转换为 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 变量提升为 is -check保护的代码中的 CirclePhoto . (类型提升相当原始,它基本上需要是您未分配的局部变量,并且您检查的类型必须是当前变量类型的子类型) .

    使 radius 私有并添加一个getter没有任何区别 . 您已经在 CirclePhoto 上有一个getter名称 radius ,这是您的最终字段引入的名称 . 将字段重命名为private并添加另一个getter没有任何优势,这是纯粹的开销 .

相关问题