是否可以覆盖 powershell 5 类中的 Getter/Setter 函数? [英] Is it possible to override the Getter/Setter functions in a powershell 5 class?

查看:89
本文介绍了是否可以覆盖 powershell 5 类中的 Getter/Setter 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始使用 powershell 5 创建类.虽然我正在遵循这个很棒的指南 https://xainey.github.io/2016/powershell-classes-and-concepts/#methods

I recently started creating classes with powershell 5. While I was following this awesome guide https://xainey.github.io/2016/powershell-classes-and-concepts/#methods

我想知道是否可以覆盖 get_xset_x 方法.

I was wondering if it is possible to override the get_x and set_x methods.

示例:

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 方法更容易:

I would like to do it because I think it would be easier for other to access the properties than using my custom Get and Set methods:

Class Foobar {
    hidden [string]$Prop1

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

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

推荐答案

不幸的是,新的 Classes 功能没有像您在 C# 中所知道的那样提供用于 getter/setter 属性的工具.

Unfortunately the new Classes feature does not have facilities for getter/setter properties like you know them from C#.

然而,您可以向现有实例添加 ScriptProperty 成员,这将表现出与 C# 中的属性类似的行为:

You can however add a ScriptProperty member to an existing instance, which will exhibit similar behavior as a Property in 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:

Now you can access $_prop1 through the Prop1 property on the object:

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

这篇关于是否可以覆盖 powershell 5 类中的 Getter/Setter 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆