使用具有自定义类型的Generic.List作为函数的返回类型不起作用



已编辑#3。

我设法使它工作起来。我需要在主脚本文件中以正确的顺序加载所有依赖项。不是来自班级档案,所以我会投票关闭这个帖子。


我在Windows 10上使用powershell 5.0。使用List(例如$list = New-Object System.Collections.Generic.List``1[CustomClass])在大多数情况下都有效。但当我将其用作返回类型时,出现了错误。

下面的代码不起作用。

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
  }
}

测试.ps1

. ".CustomClass1.ps1" 
$c1 = New-Object CustomClass1
$c1.GetColumns()

如果我把所有的类放在一个文件中,它就可以工作了。我认为这与ps1文件的加载方式有关。(感谢@jesse的提示。)

但如果我使用普通类型,如字符串、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]"表明加载类型的顺序有问题,或者您完全错过了加载依赖项(无论是脚本还是程序集)。

在使用函数之前,请检查是否已加载所有脚本和程序集。

最新更新