可以将Powershell中的null传递给需要字符串的.Net API吗?

Ric*_*erg 13 .net string powershell null

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

我错过了什么?

小智 14

要将空值传递给API调用,请使用[NullString] :: Value.


Sco*_*son 7

根据这个MS连接问题,这是一个已知问题.这里也有一些解决方法,比如使用反射来传递参数(这很聪明,但有点愚蠢,它是必需的).干杯!