Ale*_*res 2 abstraction dart flutter dart3
我最近从 Dart 2 迁移到 Dart 3,并注意到添加了类修饰符,包括接口类。它们在设置属性时工作得很好,但是当涉及到方法时,它会抛出一个错误,指出我需要将类转换为抽象类。根据逻辑,我理解接口不应该有方法体。这是一个例子:
工作正常:
interface class Foo {
late String bar;
}
Run Code Online (Sandbox Code Playgroud)
抛出 dartconcrete_class_with_abstract_member:
interface class Foo {
late String bar;
// 'getFormattedBar' must have a method body because 'Foo' isn't abstract.
// Try making 'Foo' abstract, or adding a body to 'getFormattedBar'.
// (dartconcrete_class_with_abstract_member)
String getFormattedBar();
}
Run Code Online (Sandbox Code Playgroud)
如何在 Dart 3 中声明接口方法?
我希望在接口中定义方法(当然,根据接口的定义),然后在实现类中使用各自的主体建立它们的具体实现。相反,我被迫在界面中放置一个空的主体,这没有任何意义。理想的是有这样的东西:
interface class Foo {
late String bar;
String getFormattedBar();
}
Run Code Online (Sandbox Code Playgroud)
该interface关键字确保您只能implement访问类,而不能mixin访问extend类。或者换句话说,它确保您不能从该类继承。
interface如果类修饰符是您使用的唯一类修饰符,您仍然可以构造该类。这意味着这些方法需要有具体的实现。
// Can be constructed and implemented, but not extended nor mixed in.
interface class Foo {
// Implementation needed
String bar() {
return 'baz';
}
}
Run Code Online (Sandbox Code Playgroud)
如果您还添加了abstract类修饰符,则无法构造该类,并且方法不必有具体的实现。
// Can not be constructed.
// Can be implemented, but not extended nor mixed in.
abstract interface class Foo {
// Implementation should be left out
String bar();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1564 次 |
| 最近记录: |