String.format 当字符串中有额外的 } 时抛出格式错误异常。解决此问题的最佳方法是什么?

String.format throws incorrect format exception when there is an extra } in the string. What is the best way to resolve this?

String.format 当字符串中有额外的 } 时抛出格式错误异常,如下面的代码片段所示

 var input = "1";
 var data = string.Format(@"{0}}", input);

我能够通过添加额外的 } 来解决问题,如下所示

var data = string.Format(@"{0}}}", input);

但是我想知道是否有更好的解决方案

不,这是预期的功能。来自文档:

How do I include literal braces ("{" and "}") in the result string? A single opening or closing brace is always interpreted as the beginning or end of a format item. To be interpreted literally, it must be escaped. You escape a brace by adding another brace ("{{" and "}}" instead of "{" and "}"), as in the following method call:

result = String.Format("The text has {0} '{{' characters and {1} '}}' characters.", 
             nOpen, nClose);

我强烈建议使用 C# 6 字符串插值功能,因为它更易读且更易于维护:

var data = $"{{{input}}}";

当字符串变大时,您会看到 Visual Studio 格式化和着色字符串的好处,如下所示: