【问题标题】:Powershell Call Base Class Function From Overidden FunctionPowershell 从重写函数调用基类函数
【发布时间】:2023-01-04 02:28:14
【问题描述】:

我想从其覆盖函数调用父函数,我在以下代码中隔离了我的问题:

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

【问题讨论】:

  • Object.GetType() 是非虚拟的并且不能被覆盖(尽管您可以通过多种方式隐藏它)。你到底想完成什么?

标签: powershell oop overriding base-class


【解决方案1】:

您可以通过将 $this 转换为它来完成这项工作基类, [object]:

class SomeClass  {
  [type]GetType(){
    write-host 'hooked'
    # Casting to [object] calls the original .GetType() method.
    return ([object] $this).GetType()
  }
}

[SomeClass]::new().GetType()

顺便说一句参考PowerShell中的基类custom classes:

  • 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
    
  • 在方法中身体,引用基类的唯一(非基于反射的)方法是使用输入文字,这本质上要求你硬编码基类名称(也如上面的 ([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!'
    

【讨论】:

  • 从您的回答 here 中添加基本类型的 GetMethod 是否值得?
猜你喜欢
  • 2011-05-03
  • 2011-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-19
  • 2010-09-28
相关资源
最近更新 更多