注意:这个问题已经过时了; 该
interface声明语法已经从DART中删除:
建议以消除省道接口声明
"在飞镖,每类滋生的隐式接口.现在,实现了此功能,就可以从实际的语言消除界面声明.接口声明是由纯粹的抽象类所取代."
据我所知,在Dart中实例化接口是不可能的.如果我只是尝试构造一个new MyInterface(),无论是否定义了构造函数,我都会遇到运行时错误(试一试):
NoSuchMethodException - receiver: '' function name: 'MyInterface$$Factory' arguments: []]
Run Code Online (Sandbox Code Playgroud)
interface MyInterface {}
Run Code Online (Sandbox Code Playgroud)
interface MyInterface {
MyInterface();
}
Run Code Online (Sandbox Code Playgroud)
如果我尝试使用工厂构造函数,返回一个实现的实例,我得到一个编译时错误(试一试):
SyntaxError: factory members are not allowed in interfaces
Run Code Online (Sandbox Code Playgroud)
class MyImplementation implements MyInterface {
MyImplementation();
}
interface MyInterface {
factory MyInterface() { return new MyImplementation(); }
}
Run Code Online (Sandbox Code Playgroud)
然而,这似乎在赔率与现实,即List<E>1中镖的核心库是一个接口2,但它有几个构造函数,可以被实例化.例如,这工作正常(尝试):
main() {
var list = new List();
list.add(5);
print(list.last());
}
Run Code Online (Sandbox Code Playgroud)
为什么可以List和其他许多内置接口实例化?我错过了一些方法,还是只是作为内置类型接受特殊处理?
1 Dart:Libraries:corelib:interface List <E>
2 "Dart Core Library的大部分是根据接口定义的." 3
3 Dart:教程:接口
定义接口的语法是:
interfaceDefinition:
interface identifier typeParameters? superinterfaces? factorySpecification? `{' (interfaceMemberDefinition)* `}'
Run Code Online (Sandbox Code Playgroud)
请注意,factorySpecification必须在界面的主体之前而不是在界面之内.
这就是你写它的方式:
interface MyInterface default MyImplementation {
}
class MyImplementation implements MyInterface {
MyImplementation();
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您想要完整的通用定义:
interface MyInterface<E> default MyImplementation<E> {
MyInterface(x);
}
class MyImplementation<E> implements MyInterface<E> {
MyImplementation(this.x);
E x;
}
Run Code Online (Sandbox Code Playgroud)
编辑:对于一个更完整的例子,你可以阅读的源代码interface List<E> 在https://code.google.com/p/dart/source/browse/branches/bleeding_edge/dart/corelib/src/list.dart和相关class ListFactory<T>来源位于https://code.google.com/p/dart/source/browse/branches/bleeding_edge/dart/runtime/lib/array.dart
| 归档时间: |
|
| 查看次数: |
938 次 |
| 最近记录: |