首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >$prompt = ($defaultValue,$prompt)[[bool]$prompt] -在PowerShell中模拟三元条件

$prompt = ($defaultValue,$prompt)[[bool]$prompt] -在PowerShell中模拟三元条件
EN

Stack Overflow用户
提问于 2016-11-30 15:29:10
回答 1查看 679关注 0票数 2

我正在学习用PowerShell编写脚本,我发现这段代码将帮助我完成一个项目--示例来自是否有一个一行用于使用默认值与读-主机?

代码语言:javascript
运行
复制
$defaultValue = 'default'

$prompt = Read-Host "Press enter to accept the default [$($defaultValue)]"

$prompt = ($defaultValue,$prompt)[[bool]$prompt]

我想我理解$prompt = ($defaultValue,$prompt)正在创建一个双元素数组,并且[bool]部分强制$prompt数据类型为布尔值,但我不理解第三行代码作为一个整体所做的事情。

EN

回答 1

Stack Overflow用户

发布于 2016-11-30 15:44:05

这是一种常见的编程模式:

代码语言:javascript
运行
复制
if (user entered a price)
{
    price = user entered value
} 
else
{
    price = default value
}

因为这很常见,而且也很长,有些语言有一个特殊的ternary operator,可以更简洁地编写所有的代码,并在一次移动中将一个变量赋给“这个值或那个值”。例如,在C#中,您可以编写:

代码语言:javascript
运行
复制
price = (user entered a price) ? (user entered value) : (default value)
# var = IF   [boolean test]    ? THEN  (x)          ELSE  (y)

如果测试为真,?将分配(x),如果测试为false,则分配(y)

在Python中,它被写成:

代码语言:javascript
运行
复制
price = (user entered value) if (user entered a price) else (default value)

在PowerShell中,它被写成:

代码语言:javascript
运行
复制
# you can't have a ternary operator in PowerShell, because reasons. 

嗯。不允许使用很好的短代码模式。

但是,你可以做的是滥用数组索引(@('x', 'y')[0] is 'x'@('x', 'y')[1] is 'y' ),并编写丑陋和混乱的代码-高尔夫行:

代码语言:javascript
运行
复制
$price = ($defaultValue,$userValue)[[bool]$UserEnteredPrice]

# var    (x,y) is an array         $array[ ] is array indexing
         (0,1) are the array indexes of the two values

                                    [bool]$UserEnteredPrice casts the 'test' part to a True/False value
                                    [True/False] used as indexes into an array indexing makes no sense
                                                  so they implicitly cast to integers, and become 0/1

# so if the test is true, the $UserValue is assigned to $price, and if the test fails, the $DefaultValue is assigned to price.

它的行为就像一个三值运算符,只不过它令人困惑和丑陋,而且在某些情况下,如果您不小心计算这两个数组表达式,不管选择哪个数组表达式(与实际的?运算符不同),都会让您感到困惑。

编辑:我真正应该添加的是我喜欢的PowerShell表单--您可以在PowerShell中直接分配if测试的结果,然后执行:

代码语言:javascript
运行
复制
$price = if ($userValue) { $userValue } else { $DefaultValue }

# -> 

$prompt = if ($prompt) { $prompt } else { $DefaultValue }
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40892156

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档