在使用C#的verbatim字符串时如何输入{符号

14

可能是重复问题:
如何在 .Net 中转义格式字符串中的括号

在 C# 的逐字字符串中如何输入 {}

using System;

class DoFile {

    static void Main(string[] args) {
        string templateString = @"
        \{{0}\}
        {1}
        {2}
        ";
        Console.WriteLine(templateString, "a", "b", "c");
    }
}

使用verbatim字符串时,当我使用'{'或'}'时会出现错误,我猜测是因为'{'或'}'被用于参数标记,例如{0},{1},{2}\{不能正常工作。

Unhandled Exception: System.FormatException: Input string was not in a correct format.
  at System.String.ParseFormatSpecifier (System.String str, System.Int32& ptr, System.Int32& n, System.Int32& width, System.Boolean& left_align, System.String& format) [0x00000] in <filename unknown>:0 
  at System.String.FormatHelper (System.Text.StringBuilder result, IFormatProvider provider, System.String format, System.Object[] args) [0x00000] in <filename unknown>:0 

你能加上那行出错的代码吗?看起来你使用了一种特殊对待 { 的 .Format 变体。 - n8wrl
2
这是一个问题,因为使用了Format,而不是使用原始字符串。 - jakebasile
3个回答

17

您只需要使用双花括号进行转义。

分别使用{{}}

就像下面这样:

string.Format("This is a format string for {0} with {{literal brackets}} inside", "test");

这是一个测试用的格式化字符串,其中包含{文字括号}


8

您需要使用这样的两个符号 {{ 或者 }}


0

在字符串中放置 {} 没有什么特别的,它们不需要被转义。此外,在 @ 分隔的字符串中,转义字符 \ 没有任何效果。

要在 String.Format 方法的格式中使用字面量 {},请将它们加倍。因此,您的格式字符串应为:

string templateString = @"
    {{{0}}}
    {1}
    {2}
    ";

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接