可以在dart中使用私有构造函数吗?

Ahm*_*mal 9 dart

我可以在TypeScript中执行以下操作

class Foo {
  private constructor () {}
}
Run Code Online (Sandbox Code Playgroud)

因此constructor只能从类本身内部进行访问。

如何在Dart中实现相同的功能?

小智 24

没有任何代码的方法一定是这样的

class Foo {
  Foo._();
}
Run Code Online (Sandbox Code Playgroud)


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._()只能从其类(和库)访问构造函数。

  • 您将无法为此私有构造函数编写单元测试。请记住,测试接口而不是实现。由于无法从库外部访问私有构造函数,因此在单元测试中测试私有方法将测试实现而不是接口。 (3认同)
  • 我该如何为此编写单元测试? (2认同)