有人可以解释一下为什么在下面的例子中函数退出后,属性的更新没有被保留
function CreateConfigObject
{
# base solution directory
$Config = New-Object -typename PSObject
# Build Config File Contents
$Config | Add-Member -Name MyProperty -MemberType NoteProperty -Value "Original Value"
return $Config
}
function MyFunction([ref]$obj)
{
Write-Host "Inside function Before Updating : " $obj.Value
Write-host "Are the objects equal? " $obj.Value.Equals($config.MyProperty)
$obj.Value = "New Value"
Write-Host "Inside function After Updating : " $obj.Value
}
$config = CreateConfigObject
Write-Host "Before calling function : " $config.MyProperty
MyFunction ([ref]$config.MyProperty)
Write-Host "After calling function : " $config.MyProperty
答案 0 :(得分:4)
进行了一些计算,但我得到了答案。 [ref]将对象而不是值传递给函数。所以你需要做的是将$config
传递给函数,然后引用它的值,以及该值的.MyProperty
属性。看看这个略有改动的代码,看看我的观点:
function CreateConfigObject
{
# base solution directory
$Config = New-Object -typename PSObject
# Build Config File Contents
$Config | Add-Member -Name MyProperty -MemberType NoteProperty -Value "Original Value"
return $Config
}
function MyFunction([ref]$obj)
{
Write-Host "Inside function Before Updating : " $obj.value.MyProperty
Write-host "Are the objects equal? " $obj.value.MyProperty.Equals($config.MyProperty)
$obj.value.MyProperty = "New Value"
Write-Host "Inside function After Updating : " $obj.value.MyProperty
}
$config = CreateConfigObject
Write-Host "Before calling function : " $config.MyProperty
MyFunction ([ref]$config)
Write-Host "After calling function : " $config.MyProperty
这将输出预期结果:
Before calling function : Original Value
Inside function Before Updating : Original Value
Are the objects equal? True
Inside function After Updating : New Value
After calling function : New Value