You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell自定义Student类调用GetReportLine方法返回值异常

问题排查结果
  • 核心问题来自原教程代码的拼写错误,和你对类逻辑的理解无关。

1. 导致输出异常的直接原因

你实例化时传入了5个参数,触发的是类中定义的5参数构造函数,该构造函数存在赋值错误:

Student ([string]$firstName, [string]$lastName, [int]$score, [int]$day, [int]$month) {
    $this.firstName = $firstName
    $this.lastName = $firstName # 此处错误:把firstName的值赋给了lastName属性
    $this.score = $score
    $this.birthday = (Get-Date -Minute 0 -Second 0 -Millisecond 0 -Hour 0 -Year 2003 -Day $day -Month $month)
}

将错误行修改为$this.lastName = $lastName即可解决输出Some Some的问题。

2. 额外隐藏错误

类中定义的6参数构造函数同样存在拼写问题,Get-Date的-Day参数未传入对应变量,调用该构造函数时会直接报错,需修改为如下逻辑:

Student ([string]$firstName, [string]$lastName, [int]$score, [int]$day, [int]$month, [int]$year) {
    $this.firstName = $firstName
    $this.lastName = $lastName
    $this.score = $score
    # 补全-Day和-Month的参数值
    $this.birthday = (Get-Date -minute 0 -second 0 -millisecond 0 -hour 0 -year $year -Day $day -Month $month)
}

修复后验证

修改完成后重新运行实例化代码:

$some = [Student]::new("Some", "Guy", 3, 2, 2)
$some.GetReportLine()

即可得到预期输出Some Guy。

另外当前代码中GetFullName和GetReportLine的实现逻辑完全一致,如果后续需要报表行返回分数、生日等额外信息,可以自行调整GetReportLine的返回值格式。

内容的提问来源于stack exchange,提问作者Eric Pilati

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 15:57:01