[英]How do I check if an element was created with a named constructor in dart?
[英]How do I guarantee a certain named constructor in Dart?
让我们说我有具体的类Cat,Dog和Parrot,以及以下界面:
class HasGuid {
HasGuid.fromId(String id);
}
我的目标是保证Cat,Dog和Parrot都有一个fromId
命名构造函数。 所以,我可以拨打电话:
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
正在通过网络进行呼叫,因此我将其作为Future
返回。 我基本上想要一个合同,声明任何混合/扩展/实现/任何HasGuid
类的类都将具有HasGuid
的命名构造fromId
。 fromId
T
类的fromId
将获取一个身份字符串并返回Future<T>
。
构造函数无法保证。
实例方法的接口(实现)保证。 超类(extends)或Mixins(with)也保证实例方法,而不是构造函数。
构造函数返回它自己的类型,而不是Future。
所以他们都应该有一个静态的方法或类,但不能保证。
简短的回答是你不能强制子类实现一个特定的命名构造函数......所有你能做的就是强制子类确保子类调用命名构造函数。
以下面的例子为例......
class Animal {
String name;
Animal.fromName(this.name);
}
class Dog extends Animal {
Dog.withName(String name) : super.fromName(name);
}
请注意以下内容......
Animal
没有零参数构造函数。 Dog
调用super.fromName()
构造函数,则会出现编译错误 The superclass 'Animal' doesn't have a zero argument constructor.
Dog
必须调用fromName()
构造函数...它不必调用它的命名构造函数。 在这种情况下,请注意它使用withName()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.