Correct me if I'm wrong, but shouldn't the below change each element in the array $List to 'ZZZ'?
> $List = @('a','b')
> ForEach($i In $List) { $i = 'ZZZ' }
> $List
a
b
Correct me if I'm wrong, but shouldn't the below change each element in the array $List to 'ZZZ'?
> $List = @('a','b')
> ForEach($i In $List) { $i = 'ZZZ' }
> $List
a
b
Share
Improve this question
edited Mar 26 at 20:07
Santiago Squarzon
61.6k5 gold badges24 silver badges54 bronze badges
asked Mar 26 at 18:55
Ryan.JamesRyan.James
575 bronze badges
1 Answer
Reset to default 2It would if you were dealing with mutable reference types, e.g. an array of hash tables:
$List = @{ Value = 'a' }, @{ Value = 'b' }
foreach ($i in $List) { $i.Value = 'ZZZ' }
$List
The loop modifies the original hash tables in $List
because $i
is a reference to each hash table, and hash tables are mutable reference types.
But for value types and strings in this case, which are reference types but are immutable, the assignment of $i
doesn't change the string itself, just re-assigns the variable reference to a new string.
If you used a for
loop instead of a foreach
for example, and since arrays are also reference types, you could alter their elements, but again, this doesn't mean you're altering the strings themselves, just assigning a new reference to each array element.
$List = 'a', 'b'
for($i = 0; $i -lt $List.Length; $i++) { $List[$i] = 'ZZZ' }
$List
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744131353a4559857.html
评论列表(0条)