返回Collections.Generic.List [String]时出现Powershell错误

时间:2014-05-26 01:34:41

标签: powershell

我有以下代码:

[Collections.Generic.List[String]]$script:Database = New-Object Collections.Generic.List[String]
[string]$script:DatabaseFile = "C:\NewFolder\database.csv"

function RunProgram
{
    $script:Database = getCurrentDatabase #errors after this line
}
function getCurrentDatabase
{
    [string[]]$database = Get-Content -Path $script:DatabaseFile
    [Collections.Generic.List[String]]$databaseAsList = $database
    return $databaseAsList
}

我在getCurrentDatabase返回后得到此异常:

Cannot convert the "system.object[]" value of type "system.object[]" to type "system.collections.generic.list`1[system.string]"

要使代码生效,我需要这样做:

[Collections.Generic.List[String]]$script:Database = New-Object Collections.Generic.List[String]
[string]$script:DatabaseFile = "C:\NewFolder\database.csv"

function RunProgram
{
    getCurrentDatabase #this works fine
}
function getCurrentDatabase
{
    [string[]]$database = Get-Content -Path $script:DatabaseFile
    $script:Database = $database
}

为什么第一种方式抛出该异常,但第二种方式不是?

编辑: 我使用PS版本2.0和C:\ NewFolder \ database.csv包含这一行:

Release Group,Email Address,Template ID,Date Viewed

1 个答案:

答案 0 :(得分:1)

这是人们经常旅行的事情...... 当您从函数输出集合时,PowerShell将枚举它们,将原始类型作为进程的一部分丢失。为防止它发生,您可以使用一元逗号:

function getCurrentDatabase
{
    [string[]]$database = Get-Content -Path $script:DatabaseFile
    [Collections.Generic.List[String]]$databaseAsList = $database
    , $databaseAsList
}

一元逗号应阻止PowerShell枚举您的集合(它实际上枚举了我们刚刚使用一元逗号创建的集合)。

我刚才写了一篇关于它的blog post - 应该帮助更详细地理解它。