為什么在這個例子中,"值 "為$null的[字串]鑄造引數從未拋出錯誤(空或$null),而值為"$null "的字串卻總是拋出錯誤?我想,如果傳遞一個強制性的引數,它會被檢查為$null/emptyness,因此在這些情況下總是會拋出一個錯誤:
Function test_M_NoE ( [Parameter(Mandatory=$true>>) ] [ValidateNotNullOrEmpty()] [string] $x ) {}。
# 測驗案例。取消注釋之一:
[string]$x = [string]$null。
# $x = [string]$null
# [string]$x = $null
# $x = $null
"1:"; test_M_NoE [string]$x # never error。
"2:"; test_M_NoE $x # always error[/span
uj5u.com熱心網友回復:
這樣做的原因是:
test_M_NoE [string]$x。
那就是[string]$x沒有按照你所期望的方式被解釋。
讓我們改變你的測驗函式定義,以幫助我們更好地看到實際發生的情況:
function test_M_noE {
param(
[Parameter(Mandatory=$true) ]
[ValidateNotNullOrEmpty()]。
[string]$x
)
Write-Host "傳遞的引數值是:'$x'"。
}
現在,我們再試一下:
PS ~> $x = $null
PS ~> test_M_NoE [string]$x。
傳遞的引數值是。'[string]'
啊!引數運算式[string]$x的結果不是空字串--它的結果是字面字串值[string]。
這是因為PowerShell試圖決議命令引數的方式與其他東西不同。從about_Parsing幫助主題:
引數模式是為在shell環境中決議命令的引數而設計的。所有的輸入都被視為可擴展的字串,除非它使用以下的語法之一。[...]
所以實際上,PowerShell把我們的引數運算式解釋為一個雙引號的字串:
test_M_NoE "[string]$x"/span>
在這一點上,行為是有意義的--$x是$null,所以它被評估為一個空字串,而運算式"[string]$x"的結果因此只是[string]。
在$(...)子運算式運算子中封閉引數運算式,使其作為一個值運算式而不是作為一個可擴展的字串被評估:
test_M_NoE $([string]$x)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/326675.html
標籤:
