是否可以在转义的大括号之间使用字符串内插格式复合格式



我想在转义的大括号("{{"和"}}"(之间构建具有格式化值的字符串。

我更喜欢使用格式字符串而不是 ToString(( 方法来格式化值。

    //Works fine but don't use composite format string
    $"{{{Math.PI.ToString("n2")}}}" // return {3.14}
    //Use composite format string but does not work
    $"{{{Math.PI:n2}}} // return {n2}
    //Use composite format string but does not work
    $"{{{null:n2}}} // return {
    //Use composite format string, work fine but I do not want extra space
    $"{{{Math.PI:n2} }} // return {3.14 }    
可以使用内

插字符串的FormattableString转换来调用自定义 IFormatter 来解决此问题。遗憾的是,不能使用扩展方法,因为扩展方法的目标不会发生从内插字符串到 FormattableString 的隐式转换。

public class HandleBraces : IFormatProvider, ICustomFormatter {
    public string Format(string format, object arg, IFormatProvider formatProvider) =>
        (format != null && format.EndsWith("}")) ? String.Format($"{{0:{format.Substring(0, format.Length - 1)}{'}'}", arg) + "}"
                                                 : null;
    public object GetFormat(Type formatType) => this;
    static HandleBraces HBFormatter = new HandleBraces();
    public static string Fix(FormattableString fs) => fs.ToString(HBFormatter);
}

现在您可以使用Fix

Console.WriteLine(HandleBraces.Fix($"{{{Math.PI:n2}}}"));

最新更新