在使用 進行一些測驗時Add-Member,我創建了我的實際資料的“副本”以進行測驗,但我很快發現這Add-Member實際上是在沒有被告知或要求的情況下向原始物件添加新屬性。這是預期的行為嗎?如果是,那么參考變數在 PowerShell 中如何作業?
例子:
# Create a CSV file
@'
Name,Title
Bob,President
Todd,Secretary
'@ > test.csv
# Load the CSV into an object
$Data = Import-Csv test.csv
# Create a duplicate of $Data (this must be the issue)
$NewData = $Data
# Add a new property to the $NewData object
$NewData | Add-Member ScriptProperty "First Initial" {$this.Name[0]}
# Check the original Object ($Data) and see the madness
$Data
# Viewing $Data as a table
Name Title First Initial
---- ----- -------------
Bob President B
Todd Secretary T
$Data | Get-Member
# Just confirming that there is indeed a MemberType of ScriptProperty that was added to $Data
TypeName: System.Management.Automation.PSCustomObject
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
Name NoteProperty string Name=Bob
Title NoteProperty string Title=President
First Initial ScriptProperty System.Object First Initial {get=$this.Name[0];}
uj5u.com熱心網友回復:
充實對這個問題的有用評論:
$NewData = $Data不會不復制資料,因為$Data包含參考,以一個陣列,這是一個實體.NET參考型別。相反,它是復制的參考,因此兩個變數最終都參考了完全相同的陣列。
一個簡單的(盡管低效)的方式來創建一個陣列的一個副本在PowerShell是包圍在它@(...)的陣列子運算式算子:
# Convenient, but slow with large arrays.
$NewData = @($Data)
# Faster.
$NewData = $Data.Clone()
然而,如果陣列的元素也包含參考到.NET參考型別的情況下,復制的陣列的元素仍參考同樣的情況-和[pscustomobject]實體是Import-Csv輸出確實是參考型別實體。
您可以創建副本$Data陣列和其包含下列元素,使用固有.psobject成員創建的(淺)拷貝[pscustomobject]實體:
$NewData = $Data | ForEach-Object { $_.psobject.Copy() }
但是,如前所述,.psobject.Copy()創建每個輸入物件的淺表副本[pscustomobject]。那是:
碰巧包含.NET 值型別實體的屬性會在復制的物件中產生真實的副本;同樣,字串值實際上是副本。[1]
相比之下,包含對 .NET 參考型別實體的參考的屬性會導致這些參考被復制,這意味著原始物件的屬性值和復制的物件都指向同一個實體,這意味著如果參考的實體是mutable,對它的更改反映在兩個包含物件中。
也就是說,對于通過創建的物件Import-Csv,根據定義其屬性都是strings,這不是問題。
有關更多資訊,請參閱此答案。
[1][string]在技??術上是一種參考型別,但在 .NET 中通常被視為值型別。由于字串實體根據定義是不可變的,因此您可以依賴它的任何副本來保持不變。字串永遠不能修改,只能用 )new_ 字串替換。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/348787.html
標籤:电源外壳
