【发布时间】:2019-08-04 05:02:32
【问题描述】:
我可以在 TypeScript 中执行以下操作
class Foo {
private constructor () {}
}
所以这个constructor 只能从类本身内部访问。
如何在 Dart 中实现相同的功能?
【问题讨论】:
标签: dart
我可以在 TypeScript 中执行以下操作
class Foo {
private constructor () {}
}
所以这个constructor 只能从类本身内部访问。
如何在 Dart 中实现相同的功能?
【问题讨论】:
标签: dart
只需创建一个以_开头的命名构造函数
class Foo {
Foo._() {}
}
那么构造函数Foo._() 将只能从其类(和库)中访问。
【讨论】:
Foo._() 而不会出错?
没有任何代码的方法一定是这样的
class Foo {
Foo._();
}
【讨论】:
是的,有可能,想添加更多关于它的信息。
constructor 可以使用 (_) 下划线运算符设为私有,这意味着在 dart 中是私有的。
所以一个类可以声明为
class Foo {
Foo._() {}
}
所以现在,Foo 类没有默认构造函数
Foo foo = Foo(); // It will give compile time error
同样的理论也适用于扩展类,如果私有构造函数声明在一个单独的文件中也是不可能调用的。
class FooBar extends Foo {
FooBar() : super._(); // This will give compile time error.
}
但是,如果我们分别在同一个类或文件中使用它们,上述两个功能都可以工作。
Foo foo = Foo._(); // It will work as calling from the same class
和
class FooBar extends Foo {
FooBar() : super._(); // This will work as both Foo and FooBar are declared in same file.
}
【讨论】:
只使用抽象类。 因为不能实例化抽象类
【讨论】: