String.Format方法格式化字符串时嵌入大括号的问题

代码:

1 String.Format("{0} world!","hello")

将输出 hello world!,没有问题,但是只要在第一个参数的任意位置加上一个大括号:

1 String.Format("{0} wo{rld!","hello")

就会产生一个异常,异常信息是:

Input string was not in a correct format.

原因是String.Format把大括号像普通字符串中的反斜杠一样理解,它要么就像{0}一样出现,要么就根本不要出现。如果想要把它当成普通字符,可以把它连续写两遍,或者作为另一个参数:

1 String.Format("{0} wo{{rld!","hello")
2 //or
3 String.Format("{0} wo{1}rld!","hello","{")

它们都将输出 hello wo{rld!

不过我觉得这两种写法都无法接受,明明很容易就可以区别出哪些是作为占位符,哪些是普通字符,为什么一定要这样处理大括号?比较郁闷。

原文地址:https://www.cnblogs.com/Moosdau/p/1425235.html