Ger*_*rts 2 oop powershell overriding base-class
I want to make a call to the parent function from its overidden function, i isolated my problem in the following code:
class SomeClass{
[type]GetType(){
write-host 'hooked'
return $BaseClass.GetType() # how do i call the BaseClass GetType function??
}
}
SomeClass::new().GetType()
Run Code Online (Sandbox Code Playgroud)
i am expecting an output like this:
hooked
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True SomeClass System.Object
Run Code Online (Sandbox Code Playgroud)
为了调用基类上的方法,请强制转换 $this为它(([object] $this).GetType()在您的情况下,假设您隐式派生自()):class [object]System.Object
class SomeClass {
[type]GetType(){
Write-Verbose -Verbose hooked!
# Casting to [object] calls the original .GetType() method.
return ([object] $this).GetType()
}
}
[SomeClass]::new().GetType()
Run Code Online (Sandbox Code Playgroud)
顺便提及一下 PowerShell自定义类中的基类:
PowerShell只允许您通过基类构造函数调用中的抽象标识符来引用基类base:
class Foo { [int] $Num; Foo([int] $Num) { $this.Num = $Num } }
class FooSub : Foo { FooSub() : base(42) { } } # Note the `: base(...)` part
[FooSub]::new().Num # -> 42
Run Code Online (Sandbox Code Playgroud)
在方法中,引用基类的唯一(基于非反射的)方法是通过类型文字(cast),这本质上要求您对基类名称进行硬编码(如上所示([object] $this)):
class Foo { [string] Method() { return 'hi' } }
# Note the need to name the base class explicitly, as [Foo].
class FooSub : Foo { [string] Method() { return ([Foo] $this).Method() + '!' } }
[FooSub]::new().Method() # -> 'hi!'
Run Code Online (Sandbox Code Playgroud)
警告: Windows PowerShell中似乎存在一个错误(在PowerShell (Core) 7+中不再存在),如果基类是 使用类型参数aka构造的泛型类型,[pscustomobject][psobject]则调用基类的方法会失败。在这种情况下,请使用基于反射的解决方法;例如:
class Foo : System.Collections.ObjectModel.Collection[pscustomobject] {
[void] Add([pscustomobject] $item) {
Write-Verbose -Verbose hooked!
# Use reflection to call the base class' .Add() method.
# Note: In *PowerShell Core*, this workaround isn't necessary, and the usual would work:
# ([System.Collections.ObjectModel.Collection[pscustomobject]] $this).Add($item)
# Note the use of .GetMethod() and .Invoke()
[System.Collections.ObjectModel.Collection[pscustomobject]].GetMethod('Add').Invoke($this, [object[]] $item)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
986 次 |
| 最近记录: |