sti*_*ijn 4 c# powershell string-interpolation
powershell 中典型的字符串格式(例如使用填充或指定数字)可以这样写:
>>> "x={0,5} and y={1:F3}" -f $x, $y
x= 10 and y=0.333
Run Code Online (Sandbox Code Playgroud)
但在 Powershell 中,您还可以使用字符串插值,例如
>>> $x=10
>>> $y=1/3
>>> "x=$x and y=$y"
x=10 and y=0.333333333333333
Run Code Online (Sandbox Code Playgroud)
在 C# 中,字符串插值还支持格式说明符:
> var x = 10;
> var y = 1.0/3.0;
> $"x={x,5} and y = {y:F2}";
"x= 10 and y = 0.33"
Run Code Online (Sandbox Code Playgroud)
有没有办法在 Powershell 中实现这一点?我尝试过很多组合,比如
>>> "var=$($var, 10)"
var=10 10
Run Code Online (Sandbox Code Playgroud)
但它们都不起作用。支持吗?或者有没有一种简洁的方法来调用 C# 来使用它?
更新为 Mathias 的答案,并在 Powershell 的 github 上确认,目前不支持此功能,因此我在这里提出了功能请求
支持吗?
您可能已经注意到,PowerShell 中的字符串扩展通过简单地解析嵌套在双引号字符串中的子表达式来工作 - 没有{}占位符结构。
如果您想要字符串格式化,-f这是正确的方法。
FWIW,$s -f $a直接翻译为String.Format($s, $a)调用
对于支持字符串格式化的值类型,您通常还可以ToString()使用格式字符串进行调用(就像在 C# 中一样):
PS C:\> $a = 1 / 3
PS C:\> $a.ToString("F2")
0.33
Run Code Online (Sandbox Code Playgroud)