首页 > 解决方案 > 关于 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);
}

标签: dart

解决方案


扩展方法是语法糖;它们实际上并没有向类的实例添加方法,因此如果您需要您的类符合某个接口,它们将无济于事。

我不熟悉“Swift 协议风格编程”,但通常在 Dart 中,类用于implements满足接口。例如:

abstract class delegateOne {
  String getDescriptionForIndex(int index);
}

class HomePage implements delegateOne {
  @override   
  String getDescriptionForIndex(int index) {
    // TODO: implement getDescriptionURLForIndex
    return "description";
  }
}

推荐阅读