相关疑难解决方法(0)

可以将Powershell中的null传递给需要字符串的.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;
        }
    }
}
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

我错过了什么?

.net string powershell null

13
推荐指数
2
解决办法
3086
查看次数

当绑定到参数时,如何防止字符串参数从null更改为空?

请考虑以下代码:

function f {
    param (
        [AllowNull()]
        [string]
        $x
    )
    return $x
}

$r = f -x $null
Run Code Online (Sandbox Code Playgroud)

$null到达[string]::Empty时转换为return. $null是不同的[string]::Empty,我想保留这种区别.我也更喜欢保持$x类型,[string]因为$x只有字符串的含义,接口在别处使用.

  1. 我怎样才能让$x出来作为$null当它传递$null
  2. 还有其他方法我可以告诉它不是从里面$x传递的吗?$null [string]::Emptyf

更新1

我想要做的是为其他类型.以下是相同的概念[int]:

function f { 
    param( 
        [System.Nullable[int]]$x 
    )
    return $x 
}

$r = f -x $null
Run Code Online (Sandbox Code Playgroud)

在那种情况下$r确实如此$null. $x可以是$null[int],但没有别的.对我来说似乎很奇怪,我必须允许任何物体,所以我可以通过一个 …

string parameters powershell null

6
推荐指数
1
解决办法
677
查看次数

为什么[NullString] :: Value使用断点进行不同的求值?

我在PowerShell ISE和VS Code中尝试了这个代码,结果相同.没有断点,输出是EMPTY,但是在行中有断点"NULL",输出是NULL(如预期的那样).为什么?

function demo {
    param(
        [string] $value = [NullString]::Value
    )

    if ($null -eq $value) {
        "NULL"
    } elseif ($value -eq '') {
        "EMPTY"
    } else {
        "$value"
    }
}

demo
Run Code Online (Sandbox Code Playgroud)

我现在知道,当你对参数使用类型修饰符[string]时,PowerShell总是将非字符串值(例如$ null或[NullString] :: Value)转换为(空)字符串.好吧,我可以忍受这一点,但是如果调试在这种情况下如此奇怪,那么很难自己解决这个问题.

debugging powershell breakpoints null-string

5
推荐指数
1
解决办法
165
查看次数