首页 > 解决方案 > 为什么要将值传递给超类?子类到超级

问题描述

我正在检查Equatable 包“如何使用”示例,它们将值传递给类,这个主题对我来说就像一个盲点,我到处都能看到:

import 'package:equatable/equatable.dart';

class Person extends Equatable {
  final String name;

  // why? what's happening behind the scene here?
  Person(this.name) : super([name]);
}

另一个例子

@immutable
abstract class MyEvent extends Equatable {
  MyEvent([List configs = const []]) : super(configs);
}

1-我们为什么要这样做?为什么要为抽象事物传递值?蓝图?这个有什么用?

2-为什么有时开发人员会像这样传递抽象类的值?

3-这里的幕后发生了什么?

4-这种代码的用例是什么?

多谢。

标签: oopflutterdartobject-oriented-analysis

解决方案


一个抽象的类并不排除它在 Dart 中有一些具体的成员。

以下面的类为例:

abstract class Foo {
  Foo(this.value);

  final int value;

  @override
  String toString() => value.toString();
}

虽然它是抽象的,但它具有属性的具体实现,value通过自定义构造函数进行初始化。

而且由于参数是必需的,子类必须像这样调用超级构造函数:

class Subclass extends Foo {
  Subclass(): super(42); 
}

推荐阅读