PowerShell - 如何添加私人成员? [英] PowerShell - how to add private members?
问题描述
在 PowerShell (v2) 中,如何向 PSObject 添加私有成员?
In PowerShell (v2), how do you add private members to a PSObject?
也就是说,只能在 ScriptProperty 或 ScriptMethod 中通过 $this
访问的成员.
That is, members that can only be accessed via $this
from within a ScriptProperty or ScriptMethod.
推荐答案
在引入 类 在 5.0 版中,PowerShell 扩展类型系统 (ETS) 没有与底层类型系统 (.NET/CTS) 相同的访问修饰符概念.
Prior to the introduction of classes in version 5.0, the PowerShell extended type system (ETS) doesn't have the same concept of access modifiers as the underlying type system (.NET/CTS) has.
向用户暗示不要直接使用它"的一种方法是为内部"属性添加前缀,例如 __
(双下划线):
One way of hinting at "don't use this directly" to users, would be to have a prefix for "internal" properties, like __
(double underscore):
$object = New-Object psobject -Property @{
Public = 4
__private = 9
} |Add-Member -MemberType ScriptProperty -Name Private -Value {
$this.__private
} -SecondValue {
param([int]$newValue)
if(($newValue % 3) -ne 0){
Write-Warning "Only multiples of 3 allowed"
} else {
$this.__private = $newValue
}
} -PassThru
这篇关于PowerShell - 如何添加私人成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!