我可以在TypeScript中执行以下操作
class Foo {
private constructor () {}
}
Run Code Online (Sandbox Code Playgroud)
因此constructor只能从类本身内部进行访问。
如何在Dart中实现相同的功能?
jit*_*555 23
是的,有可能,想添加更多信息。
constructor 可以使用 (_) 下划线运算符将A设为私有,这在 dart 中表示私有。
所以一个类可以声明为
class Foo {
Foo._() {}
}
Run Code Online (Sandbox Code Playgroud)
所以现在, Foo 类没有默认构造函数
Foo foo = Foo(); // It will give compile time error
Run Code Online (Sandbox Code Playgroud)
同样的理论也适用于扩展类,如果私有构造函数在单独的文件中声明,则也不可能调用它。
class FooBar extends Foo {
FooBar() : super._(); // This will give compile time error.
}
Run Code Online (Sandbox Code Playgroud)
但是如果我们分别在同一个类或文件中使用它们,上述两个功能都会起作用。
Foo foo = Foo._(); // It will work as calling from the same class
Run Code Online (Sandbox Code Playgroud)
和
class FooBar extends Foo {
FooBar() : super._(); // This will work as both Foo and FooBar are declared in same file.
}
Run Code Online (Sandbox Code Playgroud)
Mat*_*tia 21
只需创建一个以以下内容开头的命名构造函数 _
class Foo {
Foo._() {}
}
Run Code Online (Sandbox Code Playgroud)
那么Foo._()只能从其类(和库)访问构造函数。
| 归档时间: |
|
| 查看次数: |
1992 次 |
| 最近记录: |