2016-04-20 47 views
1

是否有正確/最好/任何方式使用PowerShell 5.0中的類結構來構建單例類?我已經試過這樣的事情:Powershell 5類和單身人士

class ScannerGeometry 
{ 
    [int] $EEprom;    # read eeprom 
    # .... 

    ScannerGeometry() 
    { 
     # ... fetch calibration from instrument 
    } 

    [ScannerGeometry] Instance() { 
     if ($this -eq $null) 
     { 
      $this = [ScannerGeometry]::new() 
     } 
     return $this 
    } 
} 

並賦予它的東西,如:

$scanner = [ScannerGeometry]::Instance() 

唉,我收到的Method invocation failed because [ScannerGeometry] does not contain a method named 'Instance'.

而且運行時錯誤,可能使一個構造函數(或任何其他方法)私人在PS5類?

+0

呵呵,是通過「獲取幫助about_Classes -Full」今天早些時候略讀:) –

回答

2

你的方法是這樣的可見的,因爲它不是一成不變的:

[ScannerGeometry]::new() | set x 
PS C:\Work> $x | gm 


    TypeName: ScannerGeometry 

Name  MemberType Definition 
----  ---------- ---------- 
Equals  Method  bool Equals(System.Object obj) 
GetHashCode Method  int GetHashCode() 
GetType  Method  type GetType() 
Instance Method  ScannerGeometry Instance() 
ToString Method  string ToString() 
EEprom  Property int EEprom {get;set;} 

您需要使用關鍵字static。在這種情況下,$this是無效的,所以你必須稍微改變一下代碼。下面是代碼:

class ScannerGeometry 
{ 
    [int] $EEprom;    # read eeprom 


    static [ScannerGeometry] Instance() { 
      return [ScannerGeometry]::new() 
    } 
} 

編輯

好,這裏是工作代碼:

class ScannerGeometry 
{ 
    [int] $EEprom    # read eeprom 

    static [ScannerGeometry] $instance 


    static [ScannerGeometry] GetInstance() { 
      if ([ScannerGeometry]::instance -eq $null) { [ScannerGeometry]::instance = [ScannerGeometry]::new() } 
      return [ScannerGeometry]::instance 
    } 
} 

$s = [ScannerGeometry]::GetInstance() 
+0

有幫助,但我得到一個新的/不同的實例,每次調用'[ScannerGeometry] Instance()'不是一個單身行爲。我可以使用外部變量$ Global:scannerObject = [ScannerGeometry] :: new()',但似乎...髒? –

+0

看到我編輯的答案。 – majkinetor

+2

夥計們,請原諒我的無知,但是,爲什麼你想要實例化一個'單身'? –

1

這個怎麼樣?

class ScannerGeometry 
{ 
    [int] $EEprom;    # read eeprom 
    # .... 

    ScannerGeometry() 
    { 
     # ... fetch calibration from instrument 
    } 

    [ScannerGeometry] Instance() { 
     if ($this -eq $null) 
     { 
      $this = [ScannerGeometry]::new() 
     } 
     return $this 
    } 
} 

$scangeo = [ScannerGeometry]::new().Instance() 

PS:代碼只給沒有錯誤,我完全無能的單身方面:(

Source : HSGB

+0

如果你使這個函數成爲靜態函數,你將失去引用$ this的能力。如果不進行靜態調用,則只有在調用實例化類時才能調用該方法。你想要的是每次需要引用類時都不會調用new的能力 - 即單例。 –

+0

hm,'每次你需要參考課程時都不要叫新',你能否詳細說明一下? –