我有以下代码:
[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
}为什么第一种方式会抛出异常,而第二种方式则不会?
编辑:我使用的是PSVersion2.0,C:\NewFolder\database.csv包含以下一行:
Release Group,Email Address,Template ID,Date Viewed发布于 2014-05-26 08:51:57
这是人们经常被绊倒的东西..。当您从函数PowerShell输出集合时,将枚举它们,并将原始类型松散为进程的一部分。要防止这种情况发生,可以使用一元逗号:
function getCurrentDatabase
{
[string[]]$database = Get-Content -Path $script:DatabaseFile
[Collections.Generic.List[String]]$databaseAsList = $database
, $databaseAsList
}一元逗号应该阻止PowerShell枚举您的集合(实际上它枚举了我们刚刚使用一元逗号创建的一个集合)。
不久前,我写了一篇关于它的博客帖子文章--应该有助于更详细地理解它。
https://stackoverflow.com/questions/23861623
复制相似问题