编辑#3。
我设法使其正常工作。我需要以正确的顺序在主脚本文件中加载所有依赖项。不是来自课程文件,所以我将其投票关闭这篇文章。
我在Windows 10上使用powershell 5.0。$list = New-Object System.Collections.Generic.List``1[CustomClass]
在大多数情况下,使用List(例如)均可。但是当我将其用作返回类型时出现了错误。
下面的代码不起作用。
class CustomClass1 {
[System.Collections.Generic.List``1[CustomClass]]GetColumns([string]$tableType){
$list = New-Object System.Collections.Generic.List``1[CustomClass]
return $list
}
}
编辑:#1
我在下面尝试了此代码,但效果不佳。
[System.Collections.Generic.List``1[CustomClass]]GetColumns([string]$tableType) {
$list = New-Object System.Collections.Generic.List``1[CustomClass]
$c= New-Object CustomClass
$list.Add($c)
return ,$list
}
编辑:#2
我在此仓库中推送了测试脚本https://github.com/michaelsync/powershell-scripts/tree/master/p5Class
CustomClass.ps1
class CustomClass {
[string]$ColumnName
}
CustomClass1.ps1
. ".\CustomClass.ps1"
class CustomClass1 {
[System.Collections.Generic.List``1[CustomClass]]GetColumns(){
$list = New-Object System.Collections.Generic.List``1[CustomClass]
$c = New-Object CustomClass
$list.Add($c)
return $list
}
}
Test.ps1
. ".\CustomClass1.ps1"
$c1 = New-Object CustomClass1
$c1.GetColumns()
如果我将所有类放在一个文件中,它将起作用。我认为这与ps1文件的加载方式有关。(感谢@jesse的提示。)
但是,如果我使用普通类型,例如string,int等,它就可以工作。
class CustomClass1 {
[System.Collections.Generic.List``1[string]]GetColumns([string]$tableType){
$list = New-Object System.Collections.Generic.List``1[string]
return $list
}
}
当我为通用列表分配自定义类时,它也起作用。
$list = New-Object System.Collections.Generic.List``1[CustomClass]
$c = New-Object CustomClass
$list.Add($c)
这是我们无法返回具有自定义类类型的泛型列表的已知问题吗?
您的错误“无法找到类型[CustomType]”表明类型加载的顺序存在问题,或者您错过了完全加载依赖项(无论是脚本还是程序集)。
在使用函数之前,请检查是否已加载所有脚本和程序集。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句