【问题标题】:Adding an interface to a Dart extention method向 Dart 扩展方法添加接口
【发布时间】:2021-10-13 09:44:00
【问题描述】:

是否可以向 Dart 扩展添加接口?在 Swift 中你可以这样做:

protocol MyProtocol {
  associatedtype Item
  mutating func nextItem() -> Item?
}

extension MyClass: MyProtocol {

  public typealias Item = T

  public mutating func nextItem() -> T? {
    // ...
  }
}

你如何在 Dart 中做到这一点?这似乎是不可能的:

extension MyClassExtension<T> on MyClass implements MyInterface {
  T? nextItem() {
    // ...
  }
}

【问题讨论】:

  • 不可能。 Swift 协议更像是(类 Rust)特征,它允许对协议实现进行动态调度。 Dart 没有这个,并且 Dart 扩展永远不会动态调度。

标签: dart interface extension-methods


【解决方案1】:

无法向 Dart 扩展添加接口。请参阅此处的讨论:

您必须像使用普通扩展方法一样从接口手动添加方法:

extension MyClassExtension<T> on MyClass<T> {
  T? nextItem() {
    // ...
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2021-05-24
    • 1970-01-01
    • 2013-03-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多