Powershell从重写函数调用基类函数
我想从其覆盖的函数中调用父函数,我在以下代码中隔离了我的问题:
class SomeClass{
[type]GetType(){
write-host 'hooked'
return $BaseClass.GetType() # how do i call the BaseClass GetType function??
}
}
SomeClass::new().GetType()
我期待这样的输出:
hooked
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True SomeClass System.Object
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()
i am expecting an output like this:
hooked
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True SomeClass System.Object
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为了调用基类上的方法,强制转换
$this
到它 > (([object] $this).GetType()
,在您的情况下,考虑到您的class
隐式派生自[object]
(System.Object
)):作为旁白,参考 PowerShell 中的基类 自定义类:
base
标识符来引用基类构造函数调用:在 < em>方法,引用基类的唯一(基于非反射的)方法是通过类型文字 (强制转换),本质上要求您硬编码基类名称(也如上面的
([object] $this)
所示):警告:Windows PowerShell 中似乎存在一个错误(PowerShell (Core) 7+),其中调用基类'如果基类是,方法将失败使用类型参数
[pscustomobject]
又名[psobject]
构造的通用类型。在这种情况下,请使用基于反射的解决方法;例如:In oder to call a method on the base class, cast
$this
to it (([object] $this).GetType()
, in your case, given that yourclass
implicitly derives from[object]
(System.Object
)):As an aside re referring to the base class in PowerShell custom classes:
PowerShell only allows you to reference the base class via the abstract
base
identifier in base-class constructor calls:In methods, the only (non-reflection-based) way to refer to the base class is via a type literal (cast), which in essence requires you to hard-code the base-class name (as also shown with
([object] $this)
above):Caveat: There appears to be a bug in Windows PowerShell (no longer present in PowerShell (Core) 7+), where calling a base class' method fails if the base class is a generic type that is constructed with type argument
[pscustomobject]
aka[psobject]
. Use a reflection-based workaround in that case; e.g.: