简体   繁体   English

Dart 抽象 class 与通用工厂

[英]Dart abstract class with generic factory

I have an abstract class with a generic type.我有一个泛型类型的抽象 class 。 I want this class to define a factory so if an implementing class doesn't have this defined, it gives a warning.我希望这个 class 定义一个工厂,所以如果实施 class 没有定义这个,它会发出警告。 However I can't figure out how to do this when using a generic type.但是,当使用泛型类型时,我无法弄清楚如何做到这一点。 The abstract class just keep giving me errors.抽象的 class 只是不断给我错误。

Here's my class with some examples of non-working solutions:这是我的 class 以及一些无效解决方案的示例:

abstract class Bar<T> {

  // Error: The class 'Bar' doesn't have a default constructor
  factory Bar.someFn(Map<String, dynamic> myMap) => Bar<T>(myMap);

  // Error 1: The name of a factory constructor must be the same as the name of the immediately enclosing class
  // Error 2: 'T' isn't a function.
  // Error 3: Try correcting the name to match an existing function, or define a method or function named 'T'
  factory T.someFn(Map<String, dynamic> myMap) => T(myMap);
}

Having a correct abstract class would yield the following:拥有正确的抽象 class 将产生以下结果:

// BAD!
class Foo implements Bar<Foo> {
  
  // Missing implementation of someFn
}

// OK!
class Foo implements Bar<Foo> {

  @override
  factory Foo.someFn(Map<String, dynamic> myMap) => Foo(x: myMap['x'], y: myMap['y']);
}

Is there a way to achieve what I want?有没有办法实现我想要的?

No.不。

Constructors are not inherited, they are not part of any interface, so nothing you write in the superclass will affect the constructors of the subclass.构造函数不是继承的,它们不是任何接口的一部分,因此您在超类中编写的任何内容都不会影响子类的构造函数。

Each class can define its own constructors.每个 class 都可以定义自己的构造函数。 The only thing you can do is to add a generative constructor to the superclass, then subclasses which extend the superclass (not just implement its interface), will have to call that superclass constructor as their super-constructor invocation.您唯一能做的就是向超类添加一个生成构造函数,然后扩展超类(不仅仅是实现其接口)的子类将不得不调用该超类构造函数作为它们的超构造函数调用。

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

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