PowerShell 继承:基类中具有空构造函数的目的是什么?

问题描述 投票:0回答:1

我试图理解 PowerShell 中类继承的概念。我几乎一切正常,只需要有人解释错误和我意外发现的空构造函数。

我定义了一个基类。


class Human {
    [string]$name
    [string]$gender

    Human(){}  # Comment out this line and hit error
    Human($name, $gender)
    {
        $this.name = $name
        $this.gender = $gender
    }

    [void]Speak()
    {
        Write-Host -ForegroundColor Green "I am a human"
    }
}

定义从Human类派生的Teacher类。

class Teacher : Human {
    # Don't need to repeat $name & $gender if inherit from Human class

    # Introduce new class property -> $subject
    [string]$subject

    Teacher($name, $gender, $subject)
    {
        $this.name = $name
        $this.gender = $gender
        $this.subject = $subject
    }

    # Overrides Speak() method in Human class
    [void]Speak()
    {
        Write-Host -ForegroundColor Green "I am a $($this.subject) teacher"
    }
}

$t1 = [Teacher]::new("Steven", 'Male', 'English')
$t1
$t1.Speak()

实例 $t1 在以下输出中工作得很好。

subject name   gender
------- ----   ------
English Steven Male

I am a English teacher

如果注释掉 Human 类中的

Human(){}
,我将得到以下带有错误消息的输出。尽管 PowerShell 仍然打印
$t1
$t1.Speak()
的输出。根据记录,我在 VS Code 上使用 PowerShell 7.4.2。 这里是我对类继承的参考。

MethodException: 
Line |
   8 |      {
     |      ~
     | Cannot find an overload for "new" and the argument count: "0".
powershell
1个回答
0
投票

基本上:

通过在基类中添加重载构造函数,派生类尝试继承并重载基类的默认构造函数。
但没有默认构造函数可以继承。

因此出现错误。

tl;dr:始终编写默认构造函数。

© www.soinside.com 2019 - 2024. All rights reserved.