fla*_*kes 8 inheritance class constants dart
我想创建一个类来对一些static const值进行分组。
// SomeClass.dart
class SomeClass {
static const SOME_CONST = 'some value';
}
Run Code Online (Sandbox Code Playgroud)
dart 中防止依赖代码实例化此类的惯用方法是什么?我也想阻止扩展到这个类。在Java我会做以下事情:
// SomeClass.java
public final class SomeClass {
private SomeClass () {}
public static final String SOME_CONST = 'some value';
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我能想到的只是抛出一个Exception,但我希望编译安全而不是在运行时停止代码。
class SomeClass {
SomeClass() {
throw new Exception("Instantiation of consts class not permitted");
}
...
Run Code Online (Sandbox Code Playgroud)
为您提供一个私有构造函数将使其只能在同一个文件中创建,否则它将不可见。这也可以防止用户在其他文件中扩展或混合类。请注意,在同一个文件中,您仍然可以扩展它,因为您仍然可以访问构造函数。此外,用户将始终能够实现您的类,因为所有类都定义了一个隐式接口。
class Foo {
/// Private constructor, can only be invoked inside of this file (library).
Foo._();
}
// Same file (library).
class Fizz extends Foo {
Fizz() : super._();
}
// Different file (library).
class Bar extends Foo {} // Error: Foo does not have a zero-argument constructor
class Fizz extends Object with Foo {} // Error: The class Foo cannot be used as a mixin.
// Always allowed.
class Boo implements Foo {}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1214 次 |
| 最近记录: |