gpt4 book ai didi

powershell - 是否可以覆盖 powershell 5 类中的 Getter/Setter 函数?

转载 作者:行者123 更新时间:2023-12-04 03:00:32 25 4
gpt4 key购买 nike

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

我想知道是否可以覆盖 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;}

我想这样做是因为我认为其他人访问这些属性比使用我的自定义 Get 更容易和 Set方法:
Class Foobar {
hidden [string]$Prop1

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

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

最佳答案

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

但是,您可以添加 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"

关于powershell - 是否可以覆盖 powershell 5 类中的 Getter/Setter 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40977472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com