【发布时间】:2021-12-20 14:13:43
【问题描述】:
我有非常奇怪的行为,我认为这与点源有关,但我无法理解它。这是我所拥有的:
包含两个函数和一个类的脚本sourced.ps1:
class MyData {
[string] $Name
}
function withClass() {
$initialData = @{
Name1 = "1";
Name2 = "2";
}
$list = New-Object Collections.Generic.List[MyData]
foreach ($item in $initialData.Keys) {
$d = [MyData]::new()
$d.Name = $item
$list.Add($d)
}
}
function withString() {
$initialData = @{
Name1 = "1";
Name2 = "2";
}
$list = New-Object Collections.Generic.List[string]
foreach ($item in $initialData.Keys) {
$list.Add($item)
}
}
我还有一个脚本caller.ps1 点源上面的那个并调用函数:
$ErrorActionPreference = 'Stop'
. ".\sourced.ps1"
withClass
然后我通过在 shell(带有 PS Core 的 Win 终端)中执行 .\caller.ps1 来调用 caller.ps1。
这是我无法解释的行为:如果我调用.\caller.ps1,然后调用.\sourced.ps1,然后再次调用caller.ps1,我会收到错误:
Line |
14 | $list.Add($d)
| ~~~~~~~~~~~~~
| Cannot find an overload for "Add" and the argument count: "1".
但是,如果我将caller.ps1 改为调用withString 函数,那么无论我调用多少次caller.ps1 和sourced.ps1,一切正常。
此外,如果我先用withString 调用caller.ps1,然后将其更改为withClass,则不会出现任何错误。
我想使用模块会更正确,但我首先对这种奇怪行为的原因感兴趣。
【问题讨论】:
-
与问题无关,但为什么不,因为您已经在创建一个类,创建可以替换您的类的外部函数的方法?
-
这是一个主观的事情,我个人更喜欢在可能的情况下分离数据和行为并使用纯函数,因为这是在我倾向于喜欢的语言中完成的。如果我不需要访问并且不经常改变实例,我不使用方法而是使用函数。
标签: powershell powershell-core