【问题标题】:Putting { in verbatim string with C# [duplicate]使用 C# 将 { 逐字逐句输入 [重复]
【发布时间】:2011-05-13 19:36:40
【问题描述】:

可能重复:
How to escape brackets in a format string in .Net

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

using System;

class DoFile {

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

当我在逐字字符串中使用“{”或“}”时出现错误,我猜这是因为“{”或“}”用于参数标记,例如{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 的变体,它确实对待 { 特别。
  • 这是因为使用了Format,而不是因为使用了逐字字符串。

标签: c# .net stringtemplate


【解决方案1】:

你只需要用双花括号转义..

{{}} 分别..

如下图

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

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

【讨论】:

    【解决方案2】:

    你放两个这样的{{}}

    【讨论】:

      【解决方案3】:

      {} 放在一个字符串中并没有什么特别之处,它们不应该被转义。此外,转义字符\ 在@ 分隔的字符串中不起作用。

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-21
        • 2021-07-13
        • 2013-09-17
        相关资源
        最近更新 更多