API:
namespace ClassLibrary1
{
public class Class1
{
public static string Test(string input)
{
if (input == null)
return "It's null";
if (input == string.Empty)
return "It's empty";
else
return "Non-empty string of length " + input.Length;
}
}
}
Run Code Online (Sandbox Code Playgroud)
脚本:
add-type -path C:\temp\ClassLibrary1\ClassLibrary1\bin\Debug\ClassLibrary1.dll
[classlibrary1.class1]::Test($null)
[classlibrary1.class1]::Test([object]$null)
[classlibrary1.class1]::Test([psobject]$null)
[classlibrary1.class1]::Test($dummyVar)
[classlibrary1.class1]::Test($profile.dummyProperty)
Run Code Online (Sandbox Code Playgroud)
输出:
It's empty It's empty It's empty It's empty It's empty
我错过了什么?
请考虑以下代码:
function f {
param (
[AllowNull()]
[string]
$x
)
return $x
}
$r = f -x $null
Run Code Online (Sandbox Code Playgroud)
$null
到达[string]::Empty
时转换为return
. $null
是不同的[string]::Empty
,我想保留这种区别.我也更喜欢保持$x
类型,[string]
因为$x
只有字符串的含义,接口在别处使用.
$x
出来作为$null
当它传递$null
?$x
传递的吗?$null
[string]::Empty
f
更新1
我想要做的是为其他类型.以下是相同的概念[int]
:
function f {
param(
[System.Nullable[int]]$x
)
return $x
}
$r = f -x $null
Run Code Online (Sandbox Code Playgroud)
在那种情况下$r
确实如此$null
. $x
可以是$null
或[int]
,但没有别的.对我来说似乎很奇怪,我必须允许任何物体,所以我可以通过一个 …
我在PowerShell ISE和VS Code中尝试了这个代码,结果相同.没有断点,输出是EMPTY
,但是在行中有断点"NULL"
,输出是NULL
(如预期的那样).为什么?
function demo {
param(
[string] $value = [NullString]::Value
)
if ($null -eq $value) {
"NULL"
} elseif ($value -eq '') {
"EMPTY"
} else {
"$value"
}
}
demo
Run Code Online (Sandbox Code Playgroud)
我现在知道,当你对参数使用类型修饰符[string]时,PowerShell总是将非字符串值(例如$ null或[NullString] :: Value)转换为(空)字符串.好吧,我可以忍受这一点,但是如果调试在这种情况下如此奇怪,那么很难自己解决这个问题.
powershell ×3
null ×2
string ×2
.net ×1
breakpoints ×1
debugging ×1
null-string ×1
parameters ×1