Dart -通用子类列表

4c8rllxm  于 2023-07-31  发布在  其他
关注(0)|答案(1)|浏览(129)

我想知道是否有一种方法可以创建子类的引用列表,并能够在以后构造它们。
范例:

import 'package:flutter_test/flutter_test.dart';

abstract class Animal{
  abstract String sound;
}

class Dog extends Animal{
  @override
  String sound = "woaf";
}

class Cat extends Animal{
  @override
  String sound = "meow";
}

void main() {
  test('Subclasses', () {
    final l = [Dog, Cat];
    l.forEach((E) { 
      print(E().sound); // doesn't work
    });
  });
}

字符串

jfewjypa

jfewjypa1#

您可以创建子类的引用列表,并在以后使用Type引用构造它们的示例。

abstract class Animal {
  String get sound;
  
  factory Animal(Type type) {
    if (type == Dog) {
      return Dog();
    } else if (type == Cat) {
      return Cat();
    }

    throw ArgumentError('Invalid type: $type');
  }
}

class Dog implements Animal {
  @override
  String get sound => "woaf";
}

class Cat implements Animal {
  @override
  String get sound => "meow";
}

void main() {
  test('Subclasses', () {
    final l = [Dog, Cat];

    l.forEach((Type type) {
      print(Animal(type).sound);
    });
  });
}

字符串

相关问题