String.Format 和 IFormattable.ToString(您需要的格式在这里)是不同的,但相关的东西。
String.Format 需要一些带占位符的格式字符串,如果替换值实现了IFormattable 接口,它们也可以具有格式。
Console.WriteLine(String.Format("{0} KB", 42.ToString("###,###,###,##0.00")));
42的格式可以内联:
Console.WriteLine(String.Format("{0:###,###,###,##0.00} KB", 42));
可以通过插值进一步简化:
Console.WriteLine($"{42:###,###,###,##0.00} KB"));
当然,42 可以是插值中的变量($"{numValue:###,###,###,##0.00} KB}")。但是,格式字符串不能是变量,所以这不起作用:
string format = "{x} KB";
Console.WriteLine($format); // does not compile, use String.Format in this case
备注:
Console.WriteLine 也支持格式化,所以上面的例子可以这样写:
Console.WriteLine("{0:###,###,###,##0.00} KB", 42);
我使用明确的String.Format 只是为了避免混淆。
更新
如果尺寸格式来自外部来源,您不能将其内联到格式字符串中,但这不是问题。所以如果你有
string fileSizeFormat = "###,###,###,##0.00 KB";
您仍然可以使用myFloatWithFileSize.ToString(fileSizeFormat)。在这种情况下,String.Format 仅在您想将其嵌入到好句子或其他内容中时才需要:
return String.Format("The size of the file: {0}", fileSize.ToString(fileSizeFormat));
或插值:
return $"The size of the file: {fileSize.ToString(fileSizeFormat)}";