Dart 3 中的“接口类”有什么意义?

问题描述 投票:0回答:1

我一直在玩 Dart 3,并且是新类修饰符的粉丝。但是我似乎无法理解:为什么

interface class
存在?我理解
interface mixin
,因为你可以声明抽象成员。但是你不能用
interface class
做到这一点,至少在最新的 alpha 中是这样。

具体可以这样做:

interface mixin A {
  void foo();
}

abstract class B {
  void bar();
}

但是你不能这样做:

interface class C {
  void foobar(); // compilation error: needs a concrete implementation
}

拥有一个

interface class
的意义何在,您总是需要提供存根实现,然后稍后再实现它们?什么时候应该使用
interface class
而不是
interface mixin

dart class oop interface mixins
1个回答
0
投票

这篇文章涵盖了更多细节。 这个问题更广泛地回答了它。

但总而言之,我同意你的看法,这就是为什么你应该使用

abstract interface
而不仅仅是
interface
。如果你想实例化它,你只会在
interface
上使用
abstract interface

抽象接口

它是什么:更像是一个传统的界面。只能实施(不能扩展)。但是你可以定义没有主体的函数。

为什么要关心:您可以只定义“形状”而不定义任何功能。父类中没有任何隐藏内容。

// -- File a.dart
abstract interface class AbstractInterfaceClass {
  String name = 'Dave'; // Allowed
  void body() { print('body'); } // Allowed
  
  // This is a more traditional implementation
  int get myField; // Allowed
  void noBody(); // Allowed
}

// -- File b.dart
// Not allowed
class ExtensionClass extends AbstractInterfaceClass{}
// Allowed
class ConcreteClass implements InterfaceClass{
  // Have to override everything
  @override
  String name = 'ConcreteName';
  @override
  void function() { print('body'); }

  @override
  int get myField => 5
  @override
  void noBody() = print('concreteBody')
}

对比界面

// -- File a.dart
interface class InterfaceClass {
  String name = 'Dave'; // Allowed
  void body() { print('body'); } // Allowed

  int get myField; // Not allowed
  void noBody(); // Not allowed
}

// -- File b.dart
// Not allowed
class ExtensionClass extends InterfaceClass{}
// Allowed
class ConcreteClass implements InterfaceClass{
  // Have to override everything
  @override
  String name = 'ConcreteName';
  @override
  void function() { print('body'); }
}
© www.soinside.com 2019 - 2024. All rights reserved.