2016-12-05 10 views
2

私は最近、私はこの素晴らしいガイドにhttps://xainey.github.io/2016/powershell-classes-and-concepts/#methodspowershell 5クラスのGetter/Setter関数をオーバーライドできますか?

を以下ましたが、get_xset_xメソッドをオーバーライドすることが可能である場合、私は思っていたのPowerShell 5.持つクラスを作成し始めました。

例:

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

新しいクラス機能には、C#からそれらを知っているようなゲッター/セッタープロパティのための機能はありません。

あなたはしかし、C#でのプロパティと同様の挙動を示すであろう、既存のインスタンスに ScriptPropertyメンバーを追加することができます

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 Example](https://gist.github.com/OCram85/03ce8c0f881477c835e3fdfc279dfed7)のような既存のプロパティをオーバーライドできません。 – OCram85

+0

@ OCram85いいえ、私のような別の名前の隠れたバッキングフィールドを使用する必要があります例 –

関連する問題