string.format 中的转义花括号丢失。可能的 C# 错误?

Escaped curly brace in string.format gets lost. Possible C# bug?

我有这个 MSVC 2012 MCVE:

using System;

namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main(string [] args)
        {
            string result = string.Format(@"{{{0:G};{1:G}}}", foo(), bar());
            Console.WriteLine(result);
        }

        private static string foo() { return "foo"; }
        private static string bar() { return "bar"; }
    }
}

预期输出:{foo;bar}

结果:{foo;bar

将格式字符串更改为 @"{{{0:G};{1:G} }}" [添加 space] 会产生正确的输出。这可能是错误还是为什么不显示转义的右花括号?

来自Escaping Braces section on Composite Formatting

Opening and closing braces are interpreted as starting and ending a format item. Consequently, you must use an escape sequence to display a literal opening brace or closing brace. Specify two opening braces ("{{") in the fixed text to display one opening brace ("{"), or two closing braces ("}}") to display one closing brace ("}"). Braces in a format item are interpreted sequentially in the order they are encountered. Interpreting nested braces is not supported.

The way escaped braces are interpreted can lead to unexpected results. For example, consider the format item "{{{0:D}}}", which is intended to display an opening brace, a numeric value formatted as a decimal number, and a closing brace. However, the format item is actually interpreted in the following manner:

  • The first two opening braces ("{{") are escaped and yield one opening brace.

  • The next three characters ("{0:") are interpreted as the start of a format item.

  • The next character ("D") would be interpreted as the Decimal standard numeric format specifier, but the next two escaped braces ("}}") yield a single brace. Because the resulting string ("D}") is not a standard numeric format specifier, the resulting string is interpreted as a custom format string that means display the literal string "D}".

  • The last brace ("}") is interpreted as the end of the format item.

  • The final result that is displayed is the literal string, "{D}". The numeric value that was to be formatted is not displayed.

One way to write your code to avoid misinterpreting escaped braces and format items is to format the braces and format item separately.

因此您应该将其用作;

string result = string.Format(@"{0}{1:G};{2:G}{3}", "{", "foo", "bar", "}");