2016-12-05 87 views
2

我最近開始使用PowerShell 5.創建類當我在下面這真棒指南https://xainey.github.io/2016/powershell-classes-and-concepts/#methods是否有可能重寫PowerShell 5類中的Getter/Setter函數?

我想知道是否有可能重寫get_xset_x方法。

例子:

Class Foobar2 { 
    [string]$Prop1  
} 

$foo = [Foobar2]::new() 
$foo | gm 



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

我想這樣做,因爲我認爲這將是更容易爲對方不是用我的自定義GetSet方法訪問屬性:

Class Foobar { 
    hidden [string]$Prop1 

    [string] GetProp1() { 
     return $this.Prop1 
    } 

    [void] SetProp1([String]$Prop1) { 
     $this.Prop1 = $Prop1 
    } 
} 

回答

4

不幸的是,新的類功能沒有getter/setter屬性的功能,就像您從C#中瞭解的那樣。

但是,您可以一ScriptProperty成員添加到現有的實例,這將在C#中表現出類似的行爲作爲一個屬性:

Class FooBar 
{ 
    hidden [string]$_prop1 
} 

$FooBarInstance = [FooBar]::new() 
$FooBarInstance |Add-Member -Name Prop1 -MemberType ScriptProperty -Value { 
    # This is the getter 
    return $this._prop1 
} -SecondValue { 
    param($value) 
    # This is the setter 
    $this._prop1 = $value 
} 

現在你可以在對象上通過Prop1屬性訪問$_prop1

$FooBarInstance.Prop1 
$FooBarInstance.Prop1 = "New Prop1 value" 
+0

太好了。這甚至似乎工作,如果我在類構造函數中添加新的變量。不幸的是,我不能覆蓋現有的屬性,如[Gist示例](https://gist.github.com/OCram85/03ce8c0f881477c835e3fdfc279dfed7) – OCram85

+0

@ OCram85不,您必須使用隱藏的後臺字段,例 –