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;
}
}
}
脚本:
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)
输出:
It's empty It's empty It's empty It's empty It's empty
我错过了什么?
答案 0 :(得分:14)
为了将空值传递给API调用,请使用[NullString] :: Value。
答案 1 :(得分:7)
根据这个MS connect issue,这是一个已知问题。这里也有一些解决方法,比如使用反射来传递参数(这很聪明,但有点愚蠢,它是必需的)。干杯!
答案 2 :(得分:2)
这就是PowerShell的行为 - 它总是会尝试转换对象,只要它可以转换为目标类型(在本例中为字符串)。当转换为字符串对象时,PowerShell将始终将null(缺少值)转换为String.Empty。
请参阅第142页的Bruce Payette的书“Windows PowerShell in Action”.Bruce是PowerShell背后的架构师之一。
这有点记录了脚本语言的一些小问题,我们一定要注意它。