用字符串插值替换double String.Format

Bid*_*dou 9 .net c# string.format string-interpolation c#-6.0

我尝试将一行使用String.Format两次的代码迁移到新的.NET Framework 6字符串插值功能,但直到现在我还没有成功.

var result = String.Format(String.Format("{{0:{0}}}{1}", 
    strFormat, withUnit ? " Kb" : String.Empty), 
    (double)fileSize / FileSizeConstant.KO);
Run Code Online (Sandbox Code Playgroud)

一个工作的例子可能是:

var result = String.Format(String.Format("{{0:{0}}}{1}", 
   "N2", " Kb"), 1000000000 / 1048576D);
Run Code Online (Sandbox Code Playgroud)

产量:953,67 Kb

这是可能的还是我们需要在这种特殊情况下使用旧结构?

Leo*_*lev 6

主要问题在于strFormat变量,您不能将其作为格式说明符,"{((double)fileSize/FileSizeConstant.KO):strFormat}" 因为冒号格式说明符不是插值表达式的一部分,因此不会计算为字符串文字N2.来自文档:

插值字符串的结构如下:
$"<text> { <interpolation-expression> <optional-comma-field-width> <optional-colon-format> } <text> ... } "


您可以通过将格式传递给double.ToString方法将格式作为表达式的一部分:

$"{((double)fileSize/FileSizeConstant.KO).ToString(strFormat)}{(withUnit?" Kb":string.Empty)}";
Run Code Online (Sandbox Code Playgroud)