gpt4 book ai didi

c# - C#中的字符串格式化

转载 作者:行者123 更新时间:2023-11-30 15:33:20 24 4
gpt4 key购买 nike

我正在研究字符串格式“备忘单”,以便了解不同的字符串格式参数如何影响字符串输出。在处理 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} 被替换为格式 (argument 0){1:?} 被替换为 DateTime.Now (参数 1)

我试着像这样重写:

Console.WriteLine("DateTime format {0} = {1:{0}}", format, DateTime.Now);

这引发了一个 FormatException,但我想知道为什么您不能将字符串占位符嵌套在其他格式字符串占位符中。

在这种情况下,它应该将 {0} 替换为格式参数,并将 {1:{0}} 替换为 DateTime.Now , 后跟一个冒号和格式参数。

这在 C# 中是不可能的吗?

编辑:

就此而言,为什么 Console.WriteLine("{{0}}", "Hello World"); 导致 "{0}" 而不是“{Hello World}”?

最佳答案

我们如何简化一下?当语法声明 {{ 表示单个文字 { 时,您正试图嵌套大括号。这就是您要找的:

Console.WriteLine("DateTime format {0} = {1}", format, DateTime.Now.ToString(format));

然后回答这个问题:

For that matter, why does Console.WriteLine("{{0}}", "Hello World"); result in "{0}" instead of "{Hello World}"?

我重申,{{,在句法上意味着单个文字 {

现在,如果你想使用冒号语法,无论如何你都错了,它像这样工作 {100:C},它会在 a 中显示 100货币格式。但是您真的不需要在这里这样做,因为要使该格式起作用会很困难,因为您需要此 {1:{0}} 并且由于转义语法,这将失败。

关于c# - C#中的字符串格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17592845/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com