2

私は2つのコードを持っています:

# code 1:
[type]$t1 = [switch] 
# all is ok, code works as expected

#code 2:
function test ([type]$t2) {  }
test -t2 [switch]
# here we get error. can't convert from string to system.type

私は知っています、私は書くことができます:test -t2 "System.Management.Automation.SwitchParameter"、しかしそれは醜いです!! [switch]を[type]variableに設定できるのに、関数に渡せないのはなぜですか?

4

3 に答える 3

4

PowerShellを使用すると、キャストを使用して型を作成できます。

PS> [type]"switch"

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    SwitchParameter                          System.ValueType

実際に行っているのは、角かっこで囲まれた型名を渡すことです。

PS> [type]"[switch]"
Cannot convert the "[switch]" value of type "System.String" to type "System.Type".

したがって、タイプの名前だけを渡す必要があります。

test -t2 switch

また

test -t2 ([switch].fullname)
于 2012-06-13T07:45:08.457 に答える
3

あなたはこれを行うことができます:

test -t2 "switch"

または、code1の例を使用して、$t1それ自体を渡すことができます。

function test ([type]$t2) {  }
[type]$t1 = [switch] 
test -t2 $t1 
于 2012-06-13T07:40:49.277 に答える
2

テスト関数への引数を式としてラップすると、次のタイプが返されます。

function test ([type]$t2) {  }
test -t2 ([switch])
于 2012-06-13T14:40:05.727 に答える