簡體   English   中英

是否可以在 dart 中有一個私有構造函數?

[英]Is it possible to have a private constructor in dart?

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

class Foo {
  private constructor () {}
}

所以這個constructor只能從 class 本身內部訪問。

如何在 Dart 中實現相同的功能?

只需創建一個以_開頭的命名構造函數

class 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. 
  }

只需使用抽象類。 因為你不能實例化抽象類

您可以添加創建以下 class 以實現 singleton 實例

class Sample{
    factory Sample() => _this ??= Sample._();
    Sample._(); // you can add your custom code here
    static Sample _this;
}

現在在主 function 你可以調用示例構造函數

void main(){
    /// this will return the _this instace from sample class
    Sample sample = Sample(); 

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM