2016-12-05 88 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不,您必须使用隐藏的后台字段,例 –