可以将 null 从 Powershell 传递到需要字符串的 .Net API 吗?
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
我缺少什么?
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;
}
}
}
Script:
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)
Output:
It's empty It's empty It's empty It's empty It's empty
What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要将 null 值传递给 API 调用,请使用 [NullString]::Value。
In order to pass a null value to an API call, use [NullString]::Value.
根据此 MS 连接问题,这是一个已知问题。那里也发布了一些解决方法,例如使用反射来传递参数(这很聪明,但有点愚蠢,这是必需的)。干杯!
According to this MS connect issue, this is a known problem. There are a couple workarounds posted there, too, like using reflection to pass the paramaters (which is clever, but kinda silly that it's required). Cheers!
这就是 PowerShell 的行为方式 - 只要对象可转换为目标类型(在本例中为字符串),它就会始终尝试转换该对象。当转换为字符串对象时,PowerShell 始终将 null(没有值)转换为 String.Empty。
请参阅 Bruce Payette 的书“Windows PowerShell in Action”,大约第 142 页。Bruce 是 PowerShell 背后的架构师之一。
这有点像脚本语言中记录的小问题之一,我们绝对应该意识到这一点。
this is just how PowerShell behaves - it will always try to convert an object as long as it is convertible to the target type (in this case string). PowerShell will always convert null (the absence of a value) to String.Empty when casting into a string object.
Take a look at Bruce Payette's book "Windows PowerShell in Action", around page 142. Bruce is one of the architects behind PowerShell.
It's kinda one of those documented little gotchas of the scripting language, and we should definitely be aware of it.