C#中的字符串格式
本文关键字:格式 字符串 | 更新日期: 2023-09-27 18:21:54
我正在处理一个字符串格式的"备忘单",这样我就可以看到不同的字符串格式参数如何影响字符串输出。在使用DateTime
字符串格式参数时,我编写了一个小测试:
char[] dtFormats = new char[] { 'd', 'D', 'f', 'F', 'g', 'G', 'm', 'o', 'r', 's', 't', 'T', 'u', 'U', 'y' };
foreach (char format in dtFormats)
{
Console.WriteLine("DateTime format {0} = {1:" + format + "}", format, DateTime.Now);
}
它所做的只是使用每个参数显示DateTime
的所有不同格式。
除此之外,我想重点谈谈:
Console.WriteLine("DateTime format {0} = {1:" + format + "}", format, DateTime.Now);
现在我知道{0}
被替换为格式(参数0),{1:?}
被替换为DateTime.Now
(参数1)。
我试着这样重写:
Console.WriteLine("DateTime format {0} = {1:{0}}", format, DateTime.Now);
这引发了一个FormatException
,但我想知道为什么不能将字符串占位符嵌套在其他格式的字符串占位符中。
在这种情况下,它应该将{0}
替换为format参数,将{1:{0}}
替换为DateTime.Now
,后跟冒号和format参数。
这在C#中是不可能的吗?
编辑:
既然如此,为什么Console.WriteLine("{{0}}", "Hello World");
会导致"{0}"
而不是"{Hello World}"
?
我们可以稍微简化一下吗?当语法指出{{
表示单个文字{
时,您正试图嵌套大括号。这就是你想要的:
Console.WriteLine("DateTime format {0} = {1}", format, DateTime.Now.ToString(format));
为了回答这个问题:
既然如此,为什么Console.WriteLine("{{0}}","Hello World");结果是"{0}"而不是"{Hello World}"?
我重申,{{
在语法上意味着一个单独的文字{
。
现在,如果您想使用冒号语法,那么无论如何都有错误,它的工作原理与{100:C}
类似,它将以货币格式显示100
。但你真的不需要在这里这样做,因为要让这种格式发挥作用会很困难,因为你需要这个{1:{0}}
,而由于转义语法,这将失败。
它不起作用,因为双花}}
转义格式化字符串中的大括号。
正如你所发现的,这个:
string.Format("This {{is}} my {{escaped}} curlies");
很好(并导致This {is} my {escaped} curlies)
..,因为它们是转义的。如果你像现在这样嵌套它们。..解析器将不知道是否转义。
图像是解析器并遇到此问题:
Console.WriteLine("DateTime format {0} = {1:{0}}", format, DateTime.Now);
/* ^^ Okay, I'll escape this. WAIT!
.. now I have a two single
curly open braces. This is
a badly formatted format string
now.. FormatException!*/
您可以尝试以下操作:
Console.WriteLine(string.Format("DateTime format {0} = {{1:{0}}}", format), format, DateTime.Now);
在格式内部,不能引用任何参数。
确保字符不会被滥用的一个简单步骤是将要放入的内容分开:对于左侧,只引用具有尽可能少的附加信息的块;对于右侧,根据需要选择复杂的块(而不仅仅是变量)。示例:
Console.WriteLine("DateTime format {0}{1}{2}", format, " = {" + DateTime.Now, ":" + format + "}");
甚至:
Console.WriteLine("{0}{1}{2}", "DateTime format " + format, " = {" + DateTime.Now, ":" + format + "}");
你甚至可能依赖变量:
string chunk1 = "DateTime format " + format;
string chunk2 = " = {" + DateTime.Now;
string chunk3 = ":" + format + "}";
Console.WriteLine("{0}{1}{2}", chunk1, chunk2, chunk3);