调用 C# 代码时,PowerShell $null 不再为 null [英] PowerShell $null is not null any more when calling into C# code

查看:61
本文介绍了调用 C# 代码时,PowerShell $null 不再为 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 PowerShell 中可以定义 C# 代码并执行它.将 $null 传入以下最简单的函数表明非 null 被传入函数

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

如下调用会导致输出 Not Null.是 ''.这表明 $null 在 C# 中不为 null.'IsNullOrEmpty' 或 'IsNullOrWhiteSpace' 之类的方法返回 true,因此 PowerShell 必须隐式地将 $null 转换为字符串.

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)

任何想法为什么会发生这种情况,除了在 C# 中调用 String.IsNullOrEnpty 之外,是否还有更好的解决方法?注意:这与指定的Add_Type"的 C# 语言无关.我使用的是 PowerShell V5.

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.

推荐答案

显然,解决方案是如果您将 $null 传递给 [String] 参数,想要一个 $null [String]".应该使用一个特殊的 [NullString] 类.

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 >

我在 PowerShell 文档中找不到任何提到需要使用 [NullString] 的地方,NullString 类的源代码 包括解释其用途的任何注释.

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.

这篇关于调用 C# 代码时,PowerShell $null 不再为 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆