PowerShell $null is not null any more when calling into C# code

旧城冷巷雨未停 提交于 2019-12-19 21:11:32

问题


In PowerShell one can define C# code and execute it. Passing in $null into the following simplest function shows that not null gets passed into the function

Add-Type -TypeDefinition @"
public static class foo
{
public static void fooo(string a)
{
    if(a!=null)
    {
        System.Console.WriteLine("Not Null. Is '" + a + "'");
    }
}
}
"@ -Language CSharp

Calling it as follows leads to the output Not Null. Is ''. This shows that $null was not null in C#. Methods like 'IsNullOrEmpty' or 'IsNullOrWhiteSpace' return true, so PowerShell must have implicitly converted the $null into a string.

[foo]::fooo($Null)

Any ideas why this is happening and if there is a better fix apart from rather calling String.IsNullOrEnpty in C#? NB: This happens irrespective of the C# language specified 'Add_Type'. I'm using PowerShell V5.


回答1:


Evidently the solution is "don't pass $null to a [String] parameter if you want a $null [String]". There is a special [NullString] class that should be used instead.

PS > [foo]::fooo($Null)
Not Null. Is ''
PS > [foo]::fooo([NullString]::Value)
PS >

I can't find any mentions of the need to use [NullString] in the PowerShell documentation, nor does the source code for the NullString class include any comments explaining its purpose.



来源:https://stackoverflow.com/questions/38958377/powershell-null-is-not-null-any-more-when-calling-into-c-sharp-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!