简体   繁体   English

如何在Dart中保证某个命名构造函数?

[英]How do I guarantee a certain named constructor in Dart?

Let us say I have the concrete classes Cat, Dog, and Parrot, and the following interface: 让我们说我有具体的类Cat,Dog和Parrot,以及以下界面:

class HasGuid {
  HasGuid.fromId(String id);
}

My goal is to guarantee that Cat, Dog, and Parrot all have a fromId named constructor. 我的目标是保证Cat,Dog和Parrot都有一个fromId命名构造函数。 So, I can make calls like: 所以,我可以拨打电话:

Cat.fromId("Whiskers") =returns> [A Future<Cat> object with id "Whiskers"]
Dog.fromId("Fido")     =returns> [A Future<Dog> object with id "Fido"]
Parrot.fromId("Polly") =returns> [A Future<Parrot> object with id "Poly"]

fromId is making a call across the network, for this reason I return it as a Future . fromId正在通过网络进行呼叫,因此我将其作为Future返回。 I basically want a contract that states that any class that mixes/extends/implements/whatever the HasGuid class will have a named constructor of fromId . 我基本上想要一个合同,声明任何混合/扩展/实现/任何HasGuid类的类都将具有HasGuid的命名构造fromId Where fromId on class T will take an identity string and will return a Future<T> . fromId T类的fromId将获取一个身份字符串并返回Future<T>

There can be no assurance on constructor. 构造函数无法保证。

Interface(implements) assurance on instance methods. 实例方法的接口(实现)保证。 Super class(extends) or Mixins(with) also assurance on instance methods, not constructor. 超类(extends)或Mixins(with)也保证实例方法,而不是构造函数。

Constructor return it's own type, not a Future. 构造函数返回它自己的类型,而不是Future。

So they should all have a static method or class, but no guarantee. 所以他们都应该有一个静态的方法或类,但不能保证。

The short answer is that you cannot force a subclass to implement a specific named constructor ... all you can do is force the subclass to make sure the named constructor is called by the subclass. 简短的回答是你不能强制子类实现一个特定的命名构造函数......所有你能做的就是强制子类确保子类调用命名构造函数。

Take for example the following ... 以下面的例子为例......

class Animal {
  String name;

  Animal.fromName(this.name);
}

class Dog extends Animal {

  Dog.withName(String name) : super.fromName(name);
}

Note the following ... 请注意以下内容......

  1. Animal has no zero argument constructor. Animal没有零参数构造函数。
  2. If you don't call the super.fromName() constructor from Dog you will get a compile error 如果不从Dog调用super.fromName()构造函数,则会出现编译错误
The superclass 'Animal' doesn't have a zero argument constructor.
  1. Although Dog must call the fromName() constructor ... it doesn't have to call its named constructor the same. 虽然Dog必须调用fromName()构造函数...它不必调用它的命名构造函数。 In this case notice it is called withName() . 在这种情况下,请注意它使用withName()

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

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