The following PowerShell code:
class MyClass { }
class MyClass1 : MyClass {
[void] OutMsg([string] $Str) {
Write-Host -Object "MyClass1: $Str"
}
}
class MyClass2 : MyClass {
[void] OutMsg([string] $Str) {
Write-Host -Object "MyClass2: $Str"
}
}
[MyClass[]] $ClassArray = @([MyClass1]::new(), [MyClass2]::new())
$ClassArray.OutMsg('TestString')
outputs:
MyClass1: TestString
MyClass2: TestString
Calling
Get-Member -InputObject $ClassArray
shows me that the array object itself has no OutMsg method.
Why can I call $ClassArray.OutMsg('') though (looks like this calls the OutMsg method of each array member in turn)?
That is actually a well defined behavior of arrays in PowerShell.
To quote the documentation:
Starting in PowerShell 3.0, when you use the member-access operator to access a member that doesn't exist on a list collection, PowerShell automatically enumerates the items in the collection and attempts to access the specified member on each item.
You can find additional details in the about member-access enumeration page.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With