将动态数字格式插入插值字符串

4
C# 6.0引入了一种新的格式化操作,使用符号$表示。相比之前的方式,现在可以这样写:
String lastName = "Doena";
String firstName = "DJ";

Console.WriteLine(String.Format("{1} {0}", lastName, firstName));

你可以做到这一点

Console.WriteLine($"{firstName} {lastName}");

但是数字格式怎么办呢?如果我有这样一个例子:

Decimal price = 9999.95m;
Decimal freebie = 0;

const String format = "#,##0.##";

Console.WriteLine(String.Format("{0:" + format + "}\t{1:" + format + "}", price, freebie));

我尝试了这个:
Console.WriteLine($"{price:"{format}"}\t{freebie:"{format}"}");

和这个:

Console.WriteLine($"{price:{format}}\t{freebie:{format}}");

和这个:

Console.WriteLine($"{price:format}\t{freebie:format}");

但是它们要么无法编译,要么没有带来期望的结果。

有什么想法吗?

编辑 Howwie的答案似乎是在这里走得通的合理方式:

Console.WriteLine($"{price.ToString(format)}\t{freebie.ToString(format)}");

1
基本上你不能这样做。你必须显式地调用 string.Format - Jon Skeet
这与C# 6.0无关。这就像问为什么在以前的版本中不能执行{0:{1}} - vgru
可能是 String Interpolation with format variable 的重复问题。 - Sinatr
3
@Sinatr:我认为这不是那个问题的复制。那个问题暗示了要格式化的数据是动态的,而这只涉及到格式说明符是动态的。 - Jon Skeet
3
你可以使用 Console.WriteLine($"{price.ToString(format)}\t{freebie.ToString(format)}"); 来替代。 - Howwie
显示剩余2条评论
1个回答

4

Howwie的答案似乎是在这里行得通的合理方法:

Console.WriteLine($"{price.ToString(format)}\t{freebie.ToString(format)}");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接