从Powershell传递null值到期望字符串的.Net API是否可行?

15

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)

输出:

它是空的
它是空的
它是空的
它是空的
它是空的

我错过了什么?


1
这是一个很好的问题,实际上我感到有些惭愧,因为我已经成为PowerShell的狂热者两年了,并且进行了大量的PowerShell/.NET互操作,但我之前并不知道这个。 - Josh
3个回答

17
为了将空值传递给API调用,请使用[NullString] :: Value。

当然可以!NullString 是 PowerShell 3(从2012年开始)中的新功能。这就是为什么其他答案不知道 [NullString]::Value 的原因。 - Jeppe Stig Nielsen

7
根据这个MS connect问题,这是一个已知的问题。那里也发布了一些解决方法,比如使用反射来传递参数(这很聪明,但有点傻,因为它是必需的)。干杯!

您的链接指向登录页面。能否请您引用那里发布的解决方法,供那些没有MS Connect账户的人使用。 - Micha Wiedenmann

2
这只是PowerShell的行为方式 - 只要对象可以转换为目标类型(在此示例中为字符串),它就会尝试进行转换。 当将null(缺少值)强制转换为字符串对象时,PowerShell将始终将其转换为String.Empty。
请参阅Bruce Payette的书“Windows PowerShell in Action”,大约在第142页左右。 Bruce是PowerShell的架构师之一。
这是脚本语言文档中的一个小问题,我们应该注意到它。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接