Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/eclipse/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell将字符串[]转换为列表(<;字符串>;_Powershell - Fatal编程技术网

Powershell将字符串[]转换为列表(<;字符串>;

Powershell将字符串[]转换为列表(<;字符串>;,powershell,Powershell,我有以下代码: $csvUserInfo = @([IO.File]::ReadAllLines($script:EmailListCsvFile)) $x = $csvUserInfo.ToList() 当它运行时,我得到以下错误: Method invocation failed because [System.String] does not contain a method named 'ToList'. 为什么$csvUserInfo是字符串类型 [IO.File]

我有以下代码:

    $csvUserInfo = @([IO.File]::ReadAllLines($script:EmailListCsvFile))
    $x = $csvUserInfo.ToList()
当它运行时,我得到以下错误:

Method invocation failed because [System.String] does not contain a method named 'ToList'.
为什么$csvUserInfo是字符串类型

[IO.File]::ReadAllLines是否返回字符串[]


我也尝试过使用/不使用@,它没有任何区别。

它确实返回[string[],但该类型没有tolist()方法。我相信您看到的是V3中引入的自动成员枚举。V2抛出相同的错误,但对于[System.String[]


它在数组中查找该方法,但没有找到,因此尝试了成员枚举,以查看它是否是数组成员的方法。它也没有在那里找到它,这就是它放弃的地方,因此您得到了数组成员对象上的错误。

不,您是对的。如图所示,
[IO.File]::ReadAllLines
确实返回一个
字符串[]
对象。您所看到的令人困惑的错误在@mjolinor中有解释(我在这里不再重复)

相反,我将告诉您如何解决此问题。要将PowerShell中的
String[]
对象转换为
List
对象,需要显式将其强制转换为:

PS > [string[]]$array = "A","B","C"
PS > $array.Gettype()

IsPublic IsSerial Name                                     BaseType                                      
-------- -------- ----                                     --------                                      
True     True     String[]                                 System.Array                                  


PS > 
PS > [Collections.Generic.List[String]]$lst = $array
PS > $lst.GetType()

IsPublic IsSerial Name                                     BaseType                                      
-------- -------- ----                                     --------                                      
True     True     List`1                                   System.Object                                 

PS >
在您的具体情况下,代码为:

$csvUserInfo = [IO.File]::ReadAllLines($script:EmailListCsvFile)
[Collections.Generic.List[String]]$x = $csvUserInfo

只要您想知道类型是什么,就可以使用$variable.GetType().FullName。这将避免自动展开集合。要查看可用数组或集合的成员,请执行以下操作:
Get Member-Input$variableName
,而不是
$variableName | Get Member
。后者将自动展开集合,您将获得集合中包含的项目的成员信息。我非常非常喜欢它,尤其是在处理XML时。然而,回想起来,我希望此功能需要不同的语法,以便您在阅读脚本时知道正在使用此功能。不确定该语法是什么样的-可能是
$xml.doc..book.title
?为什么等效的C代码可以工作?:string[]csvUserInfo=File.ReadAllLines(EmailListCsvFile);列表x=csvUserInfo.ToList();C#!=PowerShell。它们在某种程度上很接近,但PowerShell是为管道设计的。我知道它们是不同的,但如果它们都基于.NET,为什么不工作?@Backwards\u Dave:是一个,C编译器将根据声明的对象类型和使用文件中的声明的
来解析它(假设没有找到本地方法)。PowerShell语言和.NET运行时没有使用
声明或扩展方法的概念。