How can I prevent a string argument changing from null to empty when bound to a parameter?

后端 未结 3 1932
别跟我提以往
别跟我提以往 2020-12-06 19:39

Consider the following code:

function f {
    param (
        [AllowNull()]
        [string]
        $x
    )
    return $x
}

$r = f -x $null
3条回答
  •  时光取名叫无心
    2020-12-06 20:10

    function f {
        param (
            [AllowNull()]$x
        )
        return $x
    }
    
    $r = f -x $null
    

    By removing the [string] and using [AllowNull()] the above function will now allow you to pass in a null object or an empty string. You can check for the type using $x.GetType with an if statement and determining if $x is null or an empty string.

提交回复
热议问题