2015-09-17 56 views
0

如何在PowerShell中創建長度爲$ Count的char數組?如何在PowerShell中創建可變長度的char數組?

PS C:\Users\Administrator> $Count 
415 
PS C:\Users\Administrator> $chars = New-Object System.Char ($Count) 
New-Object : Constructor not found. Cannot find an appropriate constructor for type System.Char. 
At line:1 char:10 
+ $chars = New-Object System.Char ($Count) 
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
+ CategoryInfo   : ObjectNotFound: (:) [New-Object], PSArgumentException 
+ FullyQualifiedErrorId : CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand 

I tried 
[Char[]] $chars = @(415) 

我有一個類需要一個字符數組,但我基本上通過使用字符串找到了解決方案。但我只想問一下,是否有人知道如何創建一個長度可變的空字符數組。

例如:我如何在PowerShell中做到這一點? C# - > var chars = new Char [Count];

+0

可能重複[如何在Powershell中填充一個未知長度的數組?)(http://stackoverflow.com/questions/12860830/how-do-i-populate-an-array-of-unkown-length-in-powershell) – TessellatingHeckler

回答

2

在PowerShell中5.0,你可以使用new() constructor method

PS C:\> $Count = 415 
PS C:\> $chars = [char[]]::new($Count) 
PS C:\> $chars.Count 
415 

在早期版本中,使用New-Object cmdlet,並表示要與[]數組:的

$chars = New-Object -TypeName 'char[]' -ArgumentList $Count 
+2

你可以也可以使用'[Array] :: CreateInstance([char],415)'。 – PetSerAl

+0

謝謝。 Mathias提供的兩種方法和PetSerAl提供的兩種方法都可以工作! – AdmiralThrawn

+2

@ComedianNinja如果回答了您的問題,請接受答案(左側上方/下方投票按鈕下方的複選框)。 – jpmc26