dart - 关于 dart 中 swift 样式扩展的问题,在 dart 中可以实现吗?
问题描述
我正在尝试在 dart 中进行快速协议风格的编程,因为我认为它很干净。所以问题是:假设我有一个协议,我必须在其中实现方法,所以在我使用委托的类中,我总是在主类之外有扩展并将委托方法放在里面,然后下次我什至可以将委托方法放在不同的文件中,而且它具有良好的可读性,例如:
// delegate method here
extension mainClass{
void delegateMethod(){}
}
然后我尝试在带有扩展名的 dart 中执行此操作,但主页类出现错误,因为它找不到 mixin 方法:
class HomePage with delegateOne{
libraryexample.delegate = this;
}
extension delegateMethod on HomePage {
String getDescriptionForIndex(int index) {
// TODO: implement getDescriptionURLForIndex
return "description";
}
}
mixin delegateOne {
String getDescriptionForIndex(int index);
}
解决方案
扩展方法是语法糖;它们实际上并没有向类的实例添加方法,因此如果您需要您的类符合某个接口,它们将无济于事。
我不熟悉“Swift 协议风格编程”,但通常在 Dart 中,类用于implements
满足接口。例如:
abstract class delegateOne {
String getDescriptionForIndex(int index);
}
class HomePage implements delegateOne {
@override
String getDescriptionForIndex(int index) {
// TODO: implement getDescriptionURLForIndex
return "description";
}
}
推荐阅读
- java - 大标准输出的 Gradle 堆空间问题
- c# - 使用 C# 中的线程列表同步消息
- docker - 错误:您没有在 GDB 的命令行上指定 -i=mi!在 Docker 中
- javascript - 如何插入记录并在插入后打印?
- node.js - 如何覆盖环回中默认方法的描述?
- android - Xamarin 和 httpclient 请求在模拟器中返回正常,但在设备上没有
- php - 在 RSS Feed WordPress 中仅包含带有元键“add_in_rss”的帖子
- linux - 更改根@
在 Ubuntu 18.04 中 - php - 没有传输支持给定的 Messenger DSN 原则
- vue.js - Vue.delete 或 $delete UI 未更新后