我如何直接从 class 静态方法生成哈希表?
How can I splat a hashtable directly from a class static method?
如何获得与以下内容相同的输出:
$ht = @{Object="Hi there";Foregroundcolor="Green"}
Write-Host @ht
不使用 a/the 变量 $ht
?
不要误会我的意思,我知道如何使用基本的 CMDLet。
我有一个生成动态哈希表的静态方法。
看看这个简化的示例代码:
class HashtableGenerator
{
static [hashtable]Answer()
{
return @{Object="Hallo Welt";ForegroundColor="Green"}
}
}
$ht = [HashtableGenerator]::Answer()
Write-Host @ht
这工作得很好,但是否有可能摆脱 $ht
变量,所以代码看起来 something 像这样:
Write-Host @([HashtableGenerator]::Answer()) # Doesn't work
使用哈希表传递函数参数与隐式指定它们的方式相同。哈希表键用作参数名称,其对应的哈希表值用作参数值。
Write-Host -Object 'Hi there' -Foregroundcolor 'Green'
我很确定你想要做的事情至少目前是不可能的。 Splatting 明确地特定于哈希表和数组 variables。不是 return 函数、方法等的值。Technet for splatting 有点支持这个
Splatting is a method of passing a collection of parameter values to a command as unit. PowerShell associates each value in the collection with a command parameter. Splatted parameter values are stored in named splatting variables, which look like standard variables, but begin with an At symbol (@) instead of a dollar sign ($). The At symbol tells PowerShell that you are passing a collection of values, instead of a single value.
在其外部使用 @ 将告诉 PowerShell 将结果视为数组。 IIRC 有一个半相关的功能请求直接从哈希表定义中展开,而不是先保存到变量中。
有关从变量 属性 展开的相关问题:
如何获得与以下内容相同的输出:
$ht = @{Object="Hi there";Foregroundcolor="Green"}
Write-Host @ht
不使用 a/the 变量 $ht
?
不要误会我的意思,我知道如何使用基本的 CMDLet。 我有一个生成动态哈希表的静态方法。 看看这个简化的示例代码:
class HashtableGenerator
{
static [hashtable]Answer()
{
return @{Object="Hallo Welt";ForegroundColor="Green"}
}
}
$ht = [HashtableGenerator]::Answer()
Write-Host @ht
这工作得很好,但是否有可能摆脱 $ht
变量,所以代码看起来 something 像这样:
Write-Host @([HashtableGenerator]::Answer()) # Doesn't work
使用哈希表传递函数参数与隐式指定它们的方式相同。哈希表键用作参数名称,其对应的哈希表值用作参数值。
Write-Host -Object 'Hi there' -Foregroundcolor 'Green'
我很确定你想要做的事情至少目前是不可能的。 Splatting 明确地特定于哈希表和数组 variables。不是 return 函数、方法等的值。Technet for splatting 有点支持这个
Splatting is a method of passing a collection of parameter values to a command as unit. PowerShell associates each value in the collection with a command parameter. Splatted parameter values are stored in named splatting variables, which look like standard variables, but begin with an At symbol (@) instead of a dollar sign ($). The At symbol tells PowerShell that you are passing a collection of values, instead of a single value.
在其外部使用 @ 将告诉 PowerShell 将结果视为数组。 IIRC 有一个半相关的功能请求直接从哈希表定义中展开,而不是先保存到变量中。
有关从变量 属性 展开的相关问题: